Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create child process in linux and handle possible failing

Tags:

c++

linux

fork

exec

I have parent process, that have to create few children processes. Best way I found is using fork + execl. But then parent process need to know if execl of concrete child fails or not, and I don't know how to implement that.

        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's process execl fails*/) {
                std::cout << "it failed" << std::endl
            } else {
                std::cout << "child born" << std::endl
            }
        }

I think this idea is not 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 child process will die after 100 milliseconds, I want to know that for sure as only that will happens.

I also think that creation of shared_memory or special pipe connection for such check is a Cannon against Bees.

There have to be simple solution for that, that I just didn't found yet.

What is the best way to achieve that?

like image 723
Arkady Avatar asked Nov 08 '22 14:11

Arkady


1 Answers

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

In a child: unregister signal handler, if execl() call failed you need to send SIGUSR1 to the parent.

In the parent: Every child pid we will store in std::set. When all childs are created you just create a separate thread for tracking childs. In the thread function just call wait() and remove pid from the set. Another way to listen SIGCHLD signal (but it will lead to more complex solution, so if spawn another thread is an option I'd use thread).

When the set is empty we have done.

like image 108
Vadim Key Avatar answered Nov 14 '22 23:11

Vadim Key