Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does wait() do on Unix?

Tags:

c

unix

ubuntu

wait

I was reading about the wait() function in a Unix systems book. The book contains a program which has wait(NULL) in it. I don't understand what that means. In other program there was

while(wait(NULL)>0) 

...which also made me scratch my head.

Can anybody explain what the function above is doing?

like image 311
Naruto Avatar asked Nov 04 '12 06:11

Naruto


2 Answers

man wait(2)

All of these system calls are used to wait for state changes in a child of the calling process, and obtain information about the child whose state has changed. A state change is considered to be: the child terminated; the child was stopped by a signal; or the child was resumed by a signal

So wait() allows a process to wait until one of its child processes change its state, exists for example. If waitpid() is called with a process id it waits for that specific child process to change its state, if a pid is not specified, then it's equivalent to calling wait() and it waits for any child process to change its state.

The wait() function returns child pid on success, so when it's is called in a loop like this:

while(wait(NULL)>0) 

It means wait until all child processes exit (or change state) and no more child processes are unwaited-for (or until an error occurs)

like image 165
iabdalkader Avatar answered Nov 12 '22 07:11

iabdalkader


a quick google suggests, wait(NULL) waits for any of the child processes to complete

like image 24
Aniket Inge Avatar answered Nov 12 '22 08:11

Aniket Inge