I've created a rudimentary example of monitoring a child process and restarting it when it fails or exits. What is the preferred/more robust method of doing this? Is it good practice to continuously poll for a change in status? My understanding is that I should utilize something like SIGCHLD
but have been unable to find any good examples.
I'm an embedded C coder mainly and this is my first attempt at trying to understand fork()
.The purpose of this code will eventually be to monitor a call to another program using exec()
and restart this program if and when it fails or finishes.
Edit:
After comments from @cnicutar I have rewritten the example below in a way I think makes more sense in the hope that it is of use to somebody later. I would like the parent to monitor a child process whilst foing other things and make a new call to exec
on a new fork
when the child process fails/finishes. I want to try and use unix signals to achieve this
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char *argv[])
{
pid_t cpid;
int status;
cpid = fork();
for (;;)
{
switch (cpid)
{
case -1 : //Fork failure
exit(EXIT_FAILURE);
break;
case 0 : //Child Process
exec(some function);
return 0; //exit child process
break;
default : //Parent process
if (waitpid(-1, &status, WNOHANG) != 1) cpid = fork(); //restart
//Do parent stuff here...
break;
}
}
}