For child processes, the wait()
and waitpid()
functions can be used to suspends execution of the current process until a child has exited. But this function can not be used for non-child processes.
Is there another function, which can wait for exit of any process ?
When a parent process dies before a child process, the kernel knows that it's not going to get a wait call, so instead it makes these processes "orphans" and puts them under the care of init (remember mother of all processes). Init will eventually perform the wait system call for these orphans so they can die.
If any process has no child process then wait() returns immediately “-1”.
wait waits for a child process to terminate, and returns that child process's pid . On error (eg when there are no child processes), -1 is returned. So, basically, the code keeps waiting for child processes to finish, until the wait ing errors out, and then you know they are all finished.
Nothing equivalent to wait()
. The usual practice is to poll using kill(pid, 0)
and looking for return value -1 and errno
of ESRCH
to indicate that the process is gone.
Update: Since linux kernel 5.3 there is a pidfd_open syscall, which creates an fd for a given pid, which can be polled to get notification when pid has exited.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With