Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl background process

I am trying to run a background process in perl. I create a child process, which is used to call another perl script. I want to run few lines of code parallely with this child process. And after the child process is done.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 output

before the child process
before wait command
(should wait for 20 secs and then print)
after 20 secs of waiting
like image 699
dreamer Avatar asked Dec 04 '22 13:12

dreamer


1 Answers

There are many problems with your script. Always:

use strict;
use warnings;

localising special variables is a good practice. Only a variable containing the special value undef returns false for defined. So, every other value (even a 0; which is the case here) returns true for defined. In the other script, the shebang is wrong.

#!/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";
like image 53
Alan Haggai Alavi Avatar answered Dec 13 '22 17:12

Alan Haggai Alavi