return to first page linux journal archive
keywordscontents

Listing 5. Delayed Process Allocation

/*
 * Listing 5:
 * delayed the allocation of new server processes
 * Ivan Griffin (ivan.griffin@ul.ie)
 */
#include <unistd.h>
#include <setjmp.h>
#include <signal.h>
static void _AlarmHandler(int);
jmp_buf env = { 0 };
const int NUMBER_SECONDS = 5; /* depends on 
		* particular application */ 
struct sigaction alarmAction = 
{
    _AlarmHandler, 0, SA_RESTART, NULL
};
int main(void)
{
    /*
     * usual daemon/socket stuff goes here
     */
    sigaction(SIGALRM, &alarmAction, NULL);
    for (;;)
    {
        /*
         * block here on accept() call
         */
        (void) alarm(NUMBER_SECONDS);
        if (setjmp(env) != SIGALRM)  /* if SIGALRM 
			   is returned => parent */
        {
            /*
             * request processing is performed 
             * here if slave, perhaps exit at end?
             */
        }
    }
    /* never reached */
    return 0;
}
void _AlarmHandler(int signal)
{
    int pid = fork();
    switch (pid)
    {
    case -1: perror("fork()");
             exit(1);
             break;
    case 0:  /* child */
             break;
    default: /* parent */
             longjmp(env, SIGALRM); /* indicate by 
				returning SIGALRM */
             break;
    }
}