Heh, I had to do just this sort of thing. You could probably accomplish the same goal with a bash script running as a daemon, which *could* do a ps -aux | grep <what you're looking for> and if it's not there, restart it.
However, in C - unfortunately it's not just as simple as a system call, although
you can set up a basic process monitor by using a combination of fork(), a signal handler, and waitpid().
In main(), set up a signal handler (using sigaction), and tell it to listen for 'SIGCHLD'. That way, your program will be notified whenever the child process does something (such as exit
)
Code:
#include <signal.h>
...
int main( blah blah blah) {
struct sigaction sa;
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = handler;
sigemptyset (&sa.sa_mask);
sigaction(SIGCHLD, &sa, NULL);
What gets assigned to sa_sigaction is a function pointer to the function that you want to be called whenever a signal happens. My function here's called 'handler', so that's what gets assigned.
Use fork() to fork off a child process (also in main if you wish, or in a function. There's a good reason for the function, you'll see).
Tell the child process to run whatever it is that you want. The return value of fork() to the parent will be the process' id (pid).
Whenever handler is called, it gets passed a set of parameters
Code:
void handler(int signo, siginfo_t *info, void *context) {
int code;
sig_code = info->si_code;
pid = (long)info->si_pid;
if(signo == SIGCHLD) {
if(retvalue = waitpid(pid, &code, WUNTRACED) > 0) {
if(sig_code == CLD_EXITED) { //child terminated normally
//Do something *
} else if(sig_code == CLD_DUMPED) { //child terminated abnormally, i.e. segfault
//do something *
} else if (sig_code == CLD_KILLED) { //child was killed
// do something *
} // and so on
}
*Keep what goes on in your signal handler as limited as possible; it's not technically "safe" to call many things, such as i/o, during a signal handler, in part since that function may be needed again very soon. If you're going to restart the process which died, I'd suggest calling another function, as restarting will involve another fork() [this is why i suggested a function to do the forking - you'll have to do it again in order to restart, and you can't get back up to main() to use the code you wrote there anymore].
I'm not entirely sure how clear this is turning out to be :-[ The man pages will help you *a lot* here, and absolutely feel free to ask questions. I think the bash script way is going to be easier, but the C way is a great learning experience