|
#1
|
|||
|
|||
|
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.
Code:
for (i = 0; i < 5; i++) {
if (fork() < 0) {
//print error
}
else if (fork() == 0) {
//run a program (exec(...)
}
else {
p_id = wait(&result);
}
}
Any help much appreciated. |
|
#2
|
|||
|
|||
|
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: Code:
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));
else
printf ("WTF?! stat = %d\n", stat);
}
}
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... |
![]() |
| Thread Tools | |
| Display Modes | |
|
|