views:

49

answers:

4

I can't find a good way to find out when a process exits in Linux. Does anyone have a solution for that?

One that I can think of is check process list periodically, but that is not instant and pretty expensive (have to loop over all processes each time).

Is there an interface for doing that on Linux? Something like waitpid, except something that can be used from unrelated processes?

Thanks, Boda Cydo

+1  A: 

Perhaps you can start the program together with another program, the second one doing whatever it is you want to do when the first program stops, like sending a notification etc.

Consider this very simple example:

sleep 10; echo "finished"

sleep 10 is the first process, echo "finished" the second one (Though echo is usually a shell plugin, but I hope you get the point)

ammoQ
A: 

If you know the PID of the process in question, you can check if /proc/$PID exists. That's a relatively cheap stat() call.

Marc B
That doesn't work. There may be a race condition.
bodacydo
+3  A: 

You cannot wait for an unrelated process, just children.

A simpler polling method than checking the process list, if you have permission, you can use the kill(2) system call and "send" signal 0.

From the kill(2) man page:

If sig is 0, then no signal is sent, but error checking is still performed; this can be used to check for the existence of a process ID or process group ID

camh
A: 

Another option is to have the process open an IPC object such as a unix domain socket; your watchdog process can detect when the process quits as it will immediately be closed.

MarkR