简体   繁体   English

获取Linux中的父进程状态

[英]Get parent process status in Linux

Trying to get the process status of a given process P from one of its childs P'. 尝试从其子级P'之一获取给定过程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. 我知道函数waitpid(),但是在文档中说它用于检查子进程的状态。

So is there any other way to ? 那么还有其他方法吗?

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 (ie by returning from main() or calling exit() ) then that's probably enough by itself. 如果您只需要告知孩子父母已经干净地退出了(即通过从main()返回或调用exit() ),那么这本身就足够了。 Choose a signal -- maybe SIGUSR1 or SIGUSR2 -- and have the parent register an atexit() handler that sends that signal to the children. 选择一个信号-可能是SIGUSR1SIGUSR2并让父级注册一个atexit()处理函数,将该信号发送给子级。 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. 您可以通过选择向两个(或多个)信号中的哪个信号发送给孩子来获得较粗粒度的信息,但是对于更详细的信息,您需要IPC机制。 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. 您还应该考虑到现有模型运行良好,并且已经运行了40多年。 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. 它可能确实不能满足您的需求,但是我敦促您考虑是否可以改进您所考虑的设计,以使其更完全地适合Unix模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM