Reputation: 851
I have two service running in linux, call them A
and B
. Each depends on the other, so if one crashes and restarts, the other one must be restarted immediately.
I have written a monitor program to launch and monitor the two services respectively, and the program can restart one service when it crashes.
I want to improve the monitor program so that when it finds one service has crashed, it will get the other service's PID and kill it.
Upvotes: 0
Views: 959
Reputation: 2794
The monitor process will spawn the two children using fork(2), right? If so, the parent will get back the child PID, which it can save in a variable for each child.
After spawning both processes, the parent monitor can just sit in a loop, waiting on a waitpid(2) call. Using the right options, this call can block until one of the children terminates, whereupon you get back the PID of the child as well as its exit status. Based on this, you can do a kill(2) on the other child, and re-execute the fork sequences to spawn new instances of both children.
Note that, after killing the second child, your next waitpid call will return the PID of that, rather than one of the new pair of children. So you will need to check the returned PID against those of both your current children, and ignore it if it doesn’t match.
Upvotes: 1
Reputation: 26027
There's a few great solutions that you can program specific responses to different events.
daemontools - http://cr.yp.to/daemontools.html
upstart(if you use ubuntu) - http://upstart.ubuntu.com/
supervisor - http://supervisord.org/
Upvotes: 1