0

I am trying to have a program that uses multiple forks.
I used this example to get myself started Multiple fork() Concurrency

it works perfectly as is. However, when I try to add a print statement in the child like this:

 if ((p = fork()) == 0) {
          // Child process: do your work here
        printf("child %i\n", ii);
          exit(0);
       }

The process never finishes. How can I do stuff in the child and get the parent to still finish execution of the program?

Community
  • 1
  • 1
richsoni
  • 4,188
  • 8
  • 34
  • 47
  • what happens to your processes? Do you see any output? – David Nehme Oct 01 '11 at 21:50
  • You need to show more of the code you have; the problem isn't in what you show us. It is not clear what `ii` is set to. You might want to consider using `getpid()` to print the process ID. (I can imagine ways in which `ii` is not incremented in the parent process as needed, for instance.) – Jonathan Leffler Oct 01 '11 at 21:56
  • Don't call `exit` in the child. Use `_exit`. Otherwise, the child may flush and clean resources that are still in use in the parent. This can, for example, change the current position for file descriptors the parent is using, which can cause data corruption. – David Schwartz Oct 02 '11 at 00:15

1 Answers1

3

In your example code

if (waitpid(childPids[ii], NULL, WNOHANG) == 0) {

should be

if (waitpid(childPids[ii], NULL, WNOHANG) == childPids[ii]) {

because of

waitpid(): on success, returns the process ID of the child whose state has changed; on error, -1 is returned; if WNOHANG was specified and no child(ren) specified by pid has yet changed state, then 0 is returned.

Reference: http://linux.die.net/man/2/waitpid

Matvey Aksenov
  • 3,802
  • 3
  • 23
  • 45