Best way to create a child process in linux and handle possible crashes

I have a parent process that needs to create multiple child processes. The best way I've found is to use fork + execl . But then the parent process needs to know whether execl will succeed in a particular child or not, and I don't know how to implement it.

  int pid = fork(); if (pid < 0) { std::cout << "ERROR on fork." << std::endl; } if (pid == 0) { execl("/my/program/full/path", (char *)NULL); exit(1); } else { if (/*child process execl fails*/) { std::cout << "it failed" << std::endl } else { std::cout << "child born" << std::endl } } 

I think this idea is not very good:

 int status(0); sleep(100); int res = waitpid(pid, &status, WNOHANG); if (res < 0 && errno == 10) { std::cout << "it failed" << std::endl } else { std::cout << "child born" << std::endl } 

because it’s not good to hope that the child process will die in 100 milliseconds, I want to know this for sure as soon as this happens.

I also believe that creating a shared_memory or special channel connection for such a check is Cannon vs. Bees.

There must be a simple solution for this that I have not yet found.

What is the best way to achieve this?

+5
source share
1 answer

As a general solution, you can register a signal handler (SIGUSR1) with the parent using sigaction ().

In the child: cancel the signal logger, if the call to execl () failed, you need to send SIGUSR1 to the parent element.

In the parent: we will store each child pid in std :: set. When all the children are created, you simply create a separate thread to track the children. In the stream function, just call wait () and remove the pid from the set. Another way to listen for the SIGCHLD signal (but this will lead to a more complicated solution, so if spawn another stream is an option, I would use a stream).

When the kit is empty, we are done.

+1
source

All Articles