Naz
Naz

Reputation: 67

fork() and wait() connection to pid

I know that fork() creates a child process, returns 0 to child and returns child's pid to parent.

From what I understand wait() also returns some kind of pid of the child process that's terminated. Is this the same pid as the one that's returned to parent after fork?

I don't understand how to use wait().

My textbook just shows

int ReturnCode;
while (pid!=wait(&ReturnCode));
/*the child has terminated with Returncode as its return code*/

I don't even understand what this means.

How do I use wait()? I am using execv to create a child process but I want parent to wait. Someone please explain and give an example.

Thanks

Upvotes: 0

Views: 409

Answers (2)

Ozair Kafray
Ozair Kafray

Reputation: 13549

wait() takes the address of an integer variable and returns the process ID of the completed process.

More about the wait() system call

The

while (pid!=wait(&ReturnCode));

loop is comparing the process id (pid) returned by wait() to the pid received earlier from a fork or any other process starter. If it finds out that the process that has ended IS NOT the same as the one this parent process has been waiting for, it keeps on wait()ing.

Upvotes: 0

bdonlan
bdonlan

Reputation: 231383

wait() does indeed return the PID of the child process that died. If you only have one child process, you don't really need to check the PID (do check that it's not zero or negative though; there are some conditions that may cause the wait call to fail). You can find an example here: http://www.csl.mtu.edu/cs4411/www/NOTES/process/fork/wait.html

Upvotes: 0

Related Questions