A script automatically checking the output of top, or ps, or alike will consume some CPU time. IMHO, monitoring and auto-restarting should be done by some sort of a guard process, that launches the process to be monitored as a child, and that respawns its child when it died. On Mac OS X 10.4-10.6, launchd is used for this, and on Mac OS X Server 10.2-10.3 there was a quite sophisticated watchdogd, that could do this.
I am new to FreeBSD, and unfortunately I am not aware of a utility for FreeBSD, that serves for this - for sure there is something, and I would also be interested to learn about this.
Anyway, here comes a (working) prove of the concept written in C:
Code:
//pguard.c -- process guard
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t pid;
int statloc;
do
{
if ((pid = fork()) == 0)
goto launch_child;
if (pid < 0)
return 1;
if (pid > 0)
wait(&statloc);
}
while (1);
launch_child:
execv(argv[0], &argv[1]);
return 0;
}
This would be compiled by:
[CMD=""]cc pguard.c -o pguard[/CMD]
Usage:
[CMD=""]pguard command args[/CMD]
For example, I tested it for maintaining a SSH Tunnel for MySQL database replication from one server to another.
[CMD=""]pguard /usr/bin/ssh -N -L4306:127.0.0.1:3306
tunnel@example.com > /dev/null &[/CMD]
Of course, authentication has to be done with RSA keys. Note also, that ssh is not in -f (background) mode. If the tunnel dies for some reason, pguard would respawn it.
Again, this is only a prove of the concept, it is missing error handling, and other sophisticated features like running in the background, guarding more than one process, having scheduling capabilities, etc. So, again, I would be very interested to learn about such a beast on FreeBSD.
Best regards
Rolf