Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl fork() & exec()

I'm trying to grasp the concept of fork() & exec() for my own learning purposes. I'm trying to use perl fork as a second identical process, and then use that to exec a .sh script.

If I use fork() & exec() can I get the .sh script to run in parallel to my perl script? Perl script doesn't wait on the child process and continues on its execution. So my perl script doesn't care about the output of the child process, but only that the command is valid and running. Sort of like calling the script to run in the background.

Is there some sort of safety I can implement to know that the child process exited correctly as well?

like image 408
user1539348 Avatar asked Feb 20 '23 01:02

user1539348


1 Answers

If I use fork() & exec() can I get the .sh script to run in parallel to my perl script? [...] Sort of like calling the script to run in the background.

Yes. Fork & exec is actually the way shells run commands in the background.

Is there some sort of safety I can implement to know that the child process exited correctly as well?

Yes, using waitpid() and looking at the return value stored in $?

Like @rohanpm mentioned, the perlipc man page has a lot of useful examples showing how to do this. Here is one of the most relevant, where a signal handler is set up for SIGCHLD (which will be sent to the parent when the child terminates)

use POSIX ":sys_wait_h";
$SIG{CHLD} = sub {
    while ((my $child = waitpid(-1, WNOHANG)) > 0) {
        $Kid_Status{$child} = $?;
    }
};
like image 110
François Févotte Avatar answered Feb 27 '23 17:02

François Févotte