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.
Advertisement
Answer
The code as shown would be adequate for most circumstances. If you really care about resource usage, you should be aware that you are starting (and keeping around) a thread for each process you are monitoring. If your program has an event loop anyway, that kind of thing can be avoided at the cost of some additional effort (and an increase in complexity).
Implementing this would entail the following:
- Instead of calling
system()
, usefork()
andexec()
to start the external program. Store its PID in a global table. - Set a
SIGCHLD
handler that notifies the event loop of the exit of a child, e.g. by writing a byte to a pipe monitored by the event loop. - When a child exits, run
waitpid
with theWNOHANG
flag in a loop that runs for as long as there are children to reap.waitpid()
will return the PID of the child that exited, so that you know to remove its PID from the table, and to schedule a timeout that restarts it.