Perl fork () & exec ()

I am trying to understand the concepts of fork () and exec () for my own learning purposes. I am trying to use Perl fork as a second identical process and then use it to execute a .sh script.

If I use fork () and exec (), can I run a .sh script in parallel with a perl script? The Perl script does not wait for the child process and continues to execute it. Therefore, my perl script does not care about the exit of the child process, but only that the command is valid and working. It looks like a script call to run in the background.

Is there some kind of security that I can implement to know that the child process came out correctly too?

+4
source share
2 answers

If I use fork () and exec (), can I run a .sh script in parallel with a perl script? [...] It looks like a script call to run in the background.

Yes. Fork and exec are actually the way shells run commands in the background.

Is there some kind of security that I can implement to know that the child process came out correctly too?

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

As mentioned by @rohanpm, the perlipc page has many useful examples showing how to do this. Here is one of the most relevant where the signal handler is configured for SIGCHLD (which will be sent to the parent when the child is finished)

 use POSIX ":sys_wait_h"; $SIG{CHLD} = sub { while ((my $child = waitpid(-1, WNOHANG)) > 0) { $Kid_Status{$child} = $?; } }; 
+5
source

To get waitpid so as not to wait for a child:

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

$ st is 0 if the process is still running, and pid if it is reaping.

+3
source

Source: https://habr.com/ru/post/1436237/


All Articles