Greg's Wiki has this very simple example of how to keep a server running s.t. if it exits, it is instantly restarted:
#!/bin/sh
while :; do
/my/game/server -foo -bar -baz >> /var/log/mygameserver 2>&1
done
But how about where you want to keep N servers running, s.t. if one fails, all should be restarted? http://wiki.bash-hackers.org/scripting/bashchanges says bash 4.3 will let me do
while :; do
server1 & p1=$!
server2 & p2=$!
wait -n $p1 $p2 # wait until at least one exits
kill $p1 $p2
done
but 4.3 is still in alpha, is there a way to do this with older systems?
Here's the method I came up with, based on Greg's Wiki and some help from #bash on irc.freenode.net:
and run_and_tell:
Not as nice as the bash 4.3 version, but it seems to work (e.g. testing with "sleep 9999" in run_and_tell). One annoyance is that I have to
trap 'kill $pid' EXIT
in the runner, and it seems I have to do the same in $prog, to ensure it's killed when its parent is killed.Here's an alternative version that avoids having to trap, by putting run_and_tell in its own process group:
and run_and_tell becomes just: