在 Windows 和 Linux 中如何在进程终止时收到通知?

发布于 2024-08-04 07:57:12 字数 174 浏览 2 评论 0原文

我想编写一个程序,每当该操作系统上任何正在运行的进程终止时,操作系统都应通知该程序。

如果以前存在的进程已经死亡,我不想每次都自己进行轮询和比较。我希望每当发生进程终止时操作系统都会向我的程序发出警报。

我该怎么办?一些示例代码会非常有帮助。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

海之角 2024-08-11 07:57:12

听起来你想要 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

九局 2024-08-11 07:57:12

在 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 calling WaitForSingleObject 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).

半世晨晓 2024-08-11 07:57:12

我没有准备好代码示例,但一个想法 - 在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文