Trouble with fork() & alarm()...
Hi all,
After countless hours going over my code I have no idea why it doesn't want to work...
I'm trying to use fork() to print two messages for 5 seconds each using alarm() to swap the active process to the other.
When I run my code it prints the [Parent] message alone for 5 seconds, however it continues to run simultaneously when the [Child] wakes from its initial sleep.
After 5 seconds of simultaneous processing the [Parent] continues to run alone indefinately; the [Child] never returns...
This leads me to believe that the [Parent] never enters the handler function but I can't work out why...
Code:
/* */
// Pre-processor Directives /////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
/////////////////////////////////////////////////////////////////
// Function Prototypes //////////////////////////////////////////
void handler( int );
/////////////////////////////////////////////////////////////////
// Main Function Implementation /////////////////////////////////
int i, j = 1;
int main( void )
{
if( fork() != 0 )
{
while( 1 )
{
signal( SIGALRM, handler );
if( i == 1 )
{
alarm( 5 );
i--;
}
printf( "[PARENT] Serving HTTP Session 2\n" );fflush( stdout );
}
}
else
{
sleep( 5 ); /* Allow the parent to get ready. */
while( 1 )
{
signal( SIGALRM, handler );
if( j == 1 )
{
alarm( 5 );
j--;
}
printf( "[CHILD] Serving HTTP Session 1\n" );fflush( stdout );
}
}
exit( EXIT_SUCCESS );
}
/////////////////////////////////////////////////////////////////
// Sub-function Implementation //////////////////////////////////
void handler( int SIG )
{
if( i = 0 )
i++;
if( j = 0 )
j++;
pause(); /* Pause the process until the other process sends it's alarm signal. */
signal( SIGALRM, handler );
}
/////////////////////////////////////////////////////////////////
Any thoughts?