在 Windows 和 Linux 中如何在进程终止时收到通知?
我想编写一个程序,每当该操作系统上任何正在运行的进程终止时,操作系统都应通知该程序。
如果以前存在的进程已经死亡,我不想每次都自己进行轮询和比较。我希望每当发生进程终止时操作系统都会向我的程序发出警报。
我该怎么办?一些示例代码会非常有帮助。
PS:寻找 Java/C++ 中的方法。
I want to write a program, that should be notified by O.S. whenever any running process on that OS dies.
I don't want to myself poll and compare everytime if a previously existing process has died. I want my program to be alerted by OS whenever a process termination happens.
How do I go about it? Some sample code would be very helpful.
PS: Looking for approaches in Java/C++.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来你想要 PsSetCreateProcessNotifyRoutine()。请参阅本文以开始使用:
http://www.codeproject.com/KB/threads /procmon.aspx
Sounds like you want PsSetCreateProcessNotifyRoutine(). See this article to get started:
http://www.codeproject.com/KB/threads/procmon.aspx
在 Unix 下,您可以使用 sigchld 信号来获取进程死亡的通知。然而,这要求被监视的进程是监视进程的子进程。
在 Windows 下,您可能需要拥有该进程的有效句柄。如果您使用 CreateProcess 自己生成进程,则可以免费获得句柄,否则您必须通过其他方式获取。然后可以通过在句柄上调用
WaitForSingleObject
来等待进程终止。抱歉,我没有任何示例代码。我什至不确定,在Windows下等待进程句柄实际上是在等待进程的终止(而不是其他一些“重要”条件,这会导致进程句柄进入“有信号”状态或其他状态)。
Under Unix, you could use the
sigchld
signal to get notified of the death of the process. This requires, however, that the process being monitored is a child process of the monitoring process.Under Windows, you might need to have a valid handle to the process. If you spawn the process yourself using
CreateProcess
, you get the handle for free, otherwise you must acquire by other means. It might then be possible to wait for the process to terminate by callingWaitForSingleObject
on the handle.Sorry, I don't have any example code for this. I am not even sure, that waiting on the process handle under Windows really awaits termination of the process (as opposed to some other "significant" condition, which causes the process handle to enter "signalled" state or something).
我没有准备好代码示例,但一个想法 - 在 Linux 上 - 可能是在第一次启动观察程序时找出你想要观察的进程的 ID(例如使用
$ pgrep
)然后使用 inotify 观看/proc// – 当进程终止时它会被删除。与轮询相比,这不会消耗任何大量的 CPU 资源。
现在,procfs inotify 不完全支持,所以我不能保证这种方法确实有效,但确实值得研究。
I don't have a code sample ready but one idea – on Linux – might be to find out the ID of the process you'd like to watch when first starting your watcher program (e.g. using
$ pgrep
) and then using inotify to watch/proc/<PID>/
– which gets deleted when the process dies. In contrast to polling, this doesn't cost any significant CPU resources.Now, procfs is not completely supported by inotify, so I can't guarantee this approach would actually work but it is certainly worth looking into.