Initiating Non-waiting Background Process in Perl

岁酱吖の 提交于 2019-12-06 11:52:56

The first one is designed to work that way - system executes the command and finishes for it to end.

The last two are also designed that way - exec specifically is designed to never return. It basically replaces the parent process with the child process.

However, the second one should do the trick: the command launched from the system call is shell, which is given your string to execute. Since the string ends with "&", that means the shell will launch your command as a background process, and finish its own execution after that launch.

Can you please post more code illustrating how #2 didn't work?

Also, see what happens if you try backticks or qx:

my $output = qx|perl /util/script.pl $id &|;
print $output;

Also, as a way of reducing unknowns, can you please run the following and tell me what prints:

my $output = qx|(echo "AAAAAAA"; /bin/date; sleep 5; /bin/date; echo "BBBBBBB") &|;
print $output;

Are you calling fork() before calling system or exec?

my $pid = fork();
if (defined($pid) && $pid==0) {
    # background process
    my $exit_code = system( $command );
    exit $exit_code >> 8;
}


my $pid = fork();
if (defined($pid) && $pid==0) {
    # background process
    exec( $command );
    # doesn't^H^H^H^H^H^H shouldn't return
}

You need to disassociate the child from the parent. See perldoc -q daemon. Or Proc::Daemon

Using fork is a good way to background processes:

my $pid = fork;
die "fork failed" unless defined $pid;
if ($pid == 0) {
    # child process goes here
    do '/util/script.pl';
    exit;
}
# parent process continues here
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!