perl后台进程

dre*_*mer 4 perl sleep fork background wait

我试图在perl中运行后台进程.我创建了一个子进程,用于调用另一个perl脚本.我希望与这个子进程并行运行几行代码.子进程完成后.我想打印一行代码.

主要脚本

#!/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";
Run Code Online (Sandbox Code Playgroud)

testing.pl

#!/usr/bin/perl

print "inside testing\n";

sleep(20);
Run Code Online (Sandbox Code Playgroud)

预期产出

before the child process
before wait command
(should wait for 20 secs and then print)
after 20 secs of waiting

Ala*_*avi 7

您的脚本存在许多问题.总是:

use strict;
use warnings;
Run Code Online (Sandbox Code Playgroud)

local正在使用特殊变量是一种很好的做法.只有包含特殊值的变量才会undef返回false defined.因此,每个其他值(甚至是一个0;这是这里的情况)返回true defined.在另一个剧本中,shebang是错误的.

#!/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";
Run Code Online (Sandbox Code Playgroud)


Gre*_*con 6

"后台进程"一节所述的perlipc文档读取

您可以在后台运行命令:

system("cmd &");
Run Code Online (Sandbox Code Playgroud)

命令STDOUTSTDERR(并且可能STDIN取决于你的shell)将与父命令相同.你不需要抓住SIGCHLD因为双重fork拍摄; 详见下文.

system在程序中为参数添加&符号可以大大简化主程序.

#! /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";
Run Code Online (Sandbox Code Playgroud)