Perl background process

I am trying to start a background process in perl. I am creating a child process that is used to call another perl script. I want to run several lines of code in parallel with this child process. And after the completion of the child process. I want to print a line of code.

Main script

#!/usr/bin/perl $|=1; print "before the child process\n"; my $pid = fork(); if (defined $pid) { system("perl testing.pl"); } print "before wait command\n"; wait(); print "after 20 secs of waiting\n"; 

testing.pl

 #!/usr/bin/perl print "inside testing\n"; sleep(20); 

Expected Result

  before the child process
 before wait command
 (should wait for 20 secs and then print)
 after 20 secs of waiting 
+4
source share
3 answers

There are many problems with your script. Always:

 use strict; use warnings; 

local Exclusion of special variables is good practice. Only a variable containing the special undef value returns false for defined . Thus, any other value (even 0 that takes place here) returns true for defined . In another script, shebang is incorrect.

 #!/usr/bin/perl use strict; use warnings; local $| = 1; print "Before the child process\n"; unless (fork) { system("perl testing.pl"); exit; } print "Before wait command\n"; wait; print "After 20 secs of waiting\n"; 
+7
source

The Background Processes section of the perlipc documentation reads

You can run the command in the background with:

 system("cmd &"); 

The STDOUT and STDERR commands (and possibly STDIN , depending on your shell) will match the parents. You do not need to catch SIGCHLD because of the double fork ; see below for more details.

Adding an ampersand to the system argument in your program can greatly simplify your main program.

 #! /usr/bin/env perl print "before the child process\n"; system("perl testing.pl &") == 0 or die "$0: perl exited " . ($? >> 8); print "before wait command\n"; wait; die "$0: wait: $!" if $? == -1; print "after 20 secs of waiting\n"; 
+6
source

fork Handling the return value is a bit complicated. A recent article by Aristotle contains a nice and concise icon, which in your case looks like this:

 #!/usr/bin/env perl use 5.010000; use strict; use warnings qw(all); say 'before the child process'; given (fork) { when (undef) { die "couldn't fork: $!" } when (0) { exec $^X => 'testing.pl'; } default { my $pid = $_; say 'before wait command'; waitpid $pid, 0; say 'after 20 secs of waiting'; } } 

Pay attention to the line exec $^X => '...' : the variable $ ^ X contains the full path to the current Perl executable, so a “correct version of Perl” will be guaranteed. In addition, a system call is meaningless when you first open it.

0
source

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


All Articles