fratzola
fratzola

Reputation: 21

UNIX processes: fork() and wait()

this is my question on fork() and the respective wait() that will take place:

In my main(), I call a function, let's say function() that uses the fork() system call, but I want function() to return without waiting for the children to terminate, and thus main() has to wait for them before terminating.

So, is it possible for main() to call wait() on children that have been fork()ed in the body of another function called my this main()?

If yes, do I have to pass the children's pid's to main() through a variable?

Upvotes: 2

Views: 606

Answers (2)

BRPocock
BRPocock

Reputation: 13934

If I follow the question correctly, you want to have something like this:

  • main calls function
  • function calls fork to create child/ren, and returns in the parent process
  • main later calls wait on the child/ren

This is fine… Nominally, you don't have to pass the child(ren)'s PID(s) back to main, because you can just call wait to reap any child process that happens to exist; however, to use waitid or waitpid, you would need/want to provide them back up to main. You could either return the PID to main in a structure like a linked list or NULL-terminated array, or create some kind of file-scoped or global variable to contain the list.

There's a pretty good breakdown in the Linux manual page for wait(2) (man 2 wait or so)

Upvotes: 2

nob
nob

Reputation: 1414

Yes, main can wait for children which forked in sub-functions. wait () waits for any child to terminate.

You will still want to pass the return value of fork() to the main function, because you will need it to decide whether you are the child or the parent process.

Upvotes: 1

Related Questions