Mssm
Mssm

Reputation: 787

Get parent process status in Linux

Trying to get the process status of a given process P from one of its childs P'.

I know about the function waitpid(), but in the doc, it said that it's used to check the status of a child process.

So is there any other way to ?

Upvotes: 0

Views: 608

Answers (1)

John Bollinger
John Bollinger

Reputation: 180351

There is no standard function by which a process can wait for its parent to terminate or obtain its parent's exit status. The process tree just doesn't work that way -- children notify their parents when they exit, not the other way around.

Therefore, if you want child processes to learn of their parents' demise, you must arrange for the parent to actively notify them. This seems like a job for signaling. If you need only to inform children that the parent exited cleanly (i.e. by returning from main() or calling exit()) then that's probably enough by itself. Choose a signal -- maybe SIGUSR1 or SIGUSR2 -- and have the parent register an atexit() handler that sends that signal to the children. That might or might not require the parent to keep track of its children.

Inasmuch as you mention getting the parent's exit status, however, you probably want a bit more. You can get coarse-grained information to the children by choosing which of two (or more) signals to send to them, but for more detailed information you need an IPC mechanism. You might write an exit status to shared memory or to a pipe (or to several of them), send a message to a socket or message queue, write a status to an ordinary file, or perhaps something else I haven't thought of.

You should also consider that the existing model works pretty well, and has done for 40-ish years. It may indeed not meet your needs, but I urge you to think about whether the design you have in mind could be improved to fit more cleanly into the Unix model.

Upvotes: 2

Related Questions