How to get notified when a process terminates in Windows and Linux?

冷暖自知 提交于 2019-12-12 13:22:31

问题


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++.


回答1:


Sounds like you want PsSetCreateProcessNotifyRoutine(). See this article to get started:

http://www.codeproject.com/KB/threads/procmon.aspx




回答2:


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).



来源:https://stackoverflow.com/questions/1393032/how-to-get-notified-when-a-process-terminates-in-windows-and-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!