« 9 Types of Users: El Explicito | Main | 9 Types of Users: Mad Bomber »

January 03, 2006

Forking

Q: I am writing some code that uses fork() and the output of the parent and child is getting mixed up.

A: This is to be expected given that the fork()ed process shares the standard out (stdout) and standard error (stderr) of the parent process. To get around this, the child could open some other file handle or you could make the parent wait until the child is dead. In the example code below, the first five parent messages should appear mixed with the child messages but the last five will appear *after* the child has finished. The magic bit is the waitpid() call.

Of course I have to mention the obligatory definition: Unix is where parents fork children and wait for them to die :-)

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
        int pid, i ;
        pid = fork() ;
        if (pid == 0)
        {
                /* This is the child process */
                for (i = 1; i <= 10; i++)
                {
                        fprintf(stderr, "Child message #%d\n", i) ;
                        sleep(1) ;
                }
        }
        else if (pid < 0)
        {
                /* Fork failed */
                fprintf(stderr, "Fork failed\n") ;
                exit(-1) ;
        }
        else
        {
                /* This is the parent process */
                int *status ;
                for (i = 1; i <= 5; i++)
                {
                        fprintf(stderr, "Parent message #%d\n", i) ;
                        sleep(1) ;
                }
                waitpid(pid, status, 0) ;
                for (i = 6; i <= 10; i++)
                {
                        fprintf(stderr, "Parent message #%d\n", i) ;
                        sleep(1) ;
                }
        }
        exit(0) ;
}

If you are having trouble following the code, let me know via email and I'll will walk through it...

Posted by Ozguru at January 3, 2006 06:00 AM