bodacydo
bodacydo

Reputation: 79299

How to find out when process exits in Linux?

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

Upvotes: 8

Views: 4425

Answers (4)

MarkR
MarkR

Reputation: 63538

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.

Upvotes: 2

camh
camh

Reputation: 42418

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

Upvotes: 4

Marc B
Marc B

Reputation: 360572

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

Upvotes: 1

Erich Kitzmueller
Erich Kitzmueller

Reputation: 36977

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)

Upvotes: 2

Related Questions