florgeng florgeng -4 years ago 129
C++ Question

Linux best practice to start and watch another process

In my process I need to start/restart another process.
Currently I use a thread with a tiny stack size and the following code:

void startAndMonitorA()
{
while(true)
{
system("myProcess");
LOG("myProcess crashed");
usleep(1000 * 1000);
}
}


I feel like that's not best practice. I have no idea about the resources the
std::system()
call is blocking or wasting. I'm on an embedded Linux - so in general I try to care about resources.

Answer Source

One problematic piece is restarting immediately: if the child process fails to start that is going to cause 100% CPU usage. It may be a transient error in the child process (e.g. cannot connect to a server). It may be a good idea to add a least one second pause before trying to restart.


What system call does on Linux is:

  1. Sets up signals SIGINT and SIGQUIT to be ignored.
  2. Blocks signal SIGCHLD.
  3. fork()
  4. Child process calls exec() shell, passing the command line to the shell.
  5. Parent process calls waitpid() that blocks the thread till the child process terminates.
  6. Parent process restores its signal dispositions.

If you were to re-implement the functionality of system you would probably omit step 5 (along with steps 1, 2 and 6) to avoid blocking the thread and rely on SIGCHLD to get notified when the child process has terminated and needs to be restarted.

In other words, the bare minimum would be to set up a signal handler for SIGCHLD and call fork and exec.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download