How to make process B running only while Process A is alive
-
28-06-2021 - |
문제
I have a process A that starts another process B.
Currently process B waits for a signal(WaitForSingleObject) that is signaled by the process'A ' before exiting and once the signal is set the process B exits.
However when Process A terminates or crashes unexpectedly I end up with process B still running.
How can I make B wait for the signal indefinitely except when the Process A has crashed?
In other words .. Process B should stay alive only till Process A is running.
thanks
해결책
WaitForSingleObject
on process A's process handle; it will signal when A dies.
One other way of doing it is to attach B to A as a debugger. Then you will get an event when the process has exited, and can exit in perfect synchronization.
다른 팁
When starting B
, pass it the pid of A. In B
, start a new thread that actively checks whether that pid corresponds to a running A
. When this no longer holds, exit.
You could also have tcp sockets sending heartbeat messages between the two processes and you could even extend that to where A and B are on different machines.
The simplest approach would be to use a mutex rather than an event. If process A exits, the mutex will be considered abandoned and process B's wait on the mutex will be satisfied.
Alternatively, you could give B a handle to process A and have it wait on both the event and the handle to process A. If you use this approach, the best way for B to get a handle to A is by inheritance; use DuplicateHandle (with bInheritHandle set to TRUE) in process A to convert the pseudohandle returned by GetCurrentProcess into a real handle. Pass the value of the handle to process B on the command line or in an environment variable.