4
votes

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?

2
See wait and waitpid.mob

2 Answers

5
votes

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} = $?;
    }
};
3
votes

To get waitpid to not wait for the child:

use POSIX qw/ WNOHANG /;
my $st = waitpid $pid, WNOHANG;

$st is 0 if the process is still running and the pid if it's reaped.