简体   繁体   English

如何找出Linux进程何时退出?

[英]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. 我找不到一个很好的方法来找出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? 是否有在Linux上执行此操作的界面? Something like waitpid , except something that can be used from unrelated processes? waitpid这样的东西,除了可以从不相关的进程中使用的东西?

Thanks, Boda Cydo 谢谢,Boda Cydo

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. 一种比检查进程列表更简单的轮询方法,如果您有权限,则可以使用kill(2)系统调用和“发送”信号0。

From the kill(2) man page: 来自kill(2)手册页:

If sig is 0, then no signal is sent, but error checking is still performed; 如果sig为0,则不发送信号,但仍然执行错误检查; this can be used to check for the existence of a process ID or process group ID 这可用于检查是否存在进程ID或进程组ID

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) sleep 10是第一个进程, echo "finished"第二个进程(虽然echo通常是一个shell插件,但我希望你明白这一点)

Another option is to have the process open an IPC object such as a unix domain socket; 另一个选择是让进程打开一个IPC对象,例如unix域套接字; your watchdog process can detect when the process quits as it will immediately be closed. 您的监视程序进程可以检测进程何时退出,因为它将立即关闭。

If you know the PID of the process in question, you can check if /proc/$PID exists. 如果您知道相关进程的PID,则可以检查/ proc / $ PID是否存在。 That's a relatively cheap stat() call. 这是一个相对便宜的stat()调用。

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

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