Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for exit of non-children processes

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 ?

like image 681
CsTamas Avatar asked Jul 21 '09 07:07

CsTamas


People also ask

What happens if parent process exits before the child?

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.

What happens if a process without any children calls wait ()?

If any process has no child process then wait() returns immediately “-1”.

Can we use wait () to make the child process wait for the parent process to finish?

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.


1 Answers

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.

like image 154
chaos Avatar answered Oct 10 '22 01:10

chaos