I have a problem, I have a control executables which monitor few process and if anyone died then it will restart it. On windo开发者_运维技巧ws we are doing with WaitFOrMultipleObject where process handle passed in the array of handle. If any process die we getting acknowledged by WaitForMultipleObject.
Now we have to implement it on Linux. How we will do it? Wait is only work for one process id and while we have to monitor multiple process.
Sounds like you're looking for process groups. You can waitpid(2)
for a process group using -pidgroup
(i.e. the negative value of the pid group) as the value for pid in the call, or -1
to wait for any child process.
This is one of the places where Unix falls down -- it really ought to have a notion of a file descriptor for a process, that could be passed to select
(which is the Unix equivalent of WaitForMultipleObjects
); but it doesn't.
What you do instead is install a handler for SIGCHLD
. In that handler, you call wait4
or waitpid
(whichever is more convenient; but don't try to use plain wait
, you need the options parameter) in a loop, setting the WNOHANG
flag, until it returns 0. For each child, package its PID and exit status into a structure and write that structure to a pipe. Read from that pipe in your main event loop, pull out the structures and take appropriate action. DO NOT try to respawn children (or allocate memory, or do anything besides call waitpid
and write
) from the signal handler, unless your program has nothing else to do and the "main loop" consists of calling sigsuspend
in an infinite loop.
精彩评论