A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2010-02-04 09:57 PM


Re: Creating Multiple Processes

I am having problems creating multiple forks. I want create a certain number of forks, each call a program and each wait for a different value. How is this accomplished my loop is not doing the trick.

for (i = 0; i < 5; i++) {

        if (fork() < 0) {
            //print error

        else if (fork() == 0) {
            //run a program (exec(...)

        else {
            p_id = wait(&result);

I know how to use the wait() and exec() call but can't figure out how to do this for multiple forks I need each fork to return a differnt value.

Any help much appreciated.

#2 2010-02-04 11:46 PM

From: Boston, MA
Registered: 2002-06-12
Posts: 3,839

Re: Creating Multiple Processes

You're doing two fork()'s for every time through that loop...  So, each process (child
and parent) goes on to do the second fork(), thereby creating 2 more processes,
then both going on to wait() on them...  That's surely not what you want...  Try
something like this, instead:

for (i = 0; i < 5; i++) {
    pid = fork();
    if (pid < 0) {
        perror ("fork()");
    } else if (pid == 0) {
        /* child: do the exec*()... */
        /* but, in case it fails, make sure you throw in an _exit() after it, too... */
    } else {
        /* parent */
        printf ("Waiting for child %d to die...\n", pid);
        if (waitpid (pid, &stat, 0) < 0) {
            perror ("waitpid()");
            exit (-1);
        if (WIFSIGNALED (stat))
            printf ("Child %d was killed by signal %d\n", pid, WTERMSIG (stat));
        else if (WIFSTOPPED (stat))
            printf ("Child %d was stopped by signal %d\n", pid, WSTOPSIG (stat));
        else if (WIFEXITED (stat))
            printf ("Child %d exited with return value %d\n", pid, WEXITSTATUS (stat));
            printf ("WTF?!  stat = %d\n", stat);

Of course, it seems silly to spawn the children only to have to wait serially on them
as they run...  If your intent was to spawn them all and let them run simultaneously
in the background, then wait on them all later after they're all running, you'll want to
skip the wait*() inside the loop...  Just do nothing in the parent section, then after the
loop terminates, do 5 wait()'s or waitpid(-1)'s to get their statuses...  (Or, you could
store their PIDs and specifically waitpid() on each one, if you wanted...  But, you
can't really be sure which one will exit first, so that's probably not a good idea...)
Or, you could have the parent go on and do something else, and let a SIGCHLD
signal handler notify you when each exits...


Board footer

Powered by FluxBB