加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在后台运行perl子例程

发布时间:2020-12-15 21:48:24 所属栏目:大数据 来源:网络整理
导读:有没有办法在后台运行perl子程序?我环顾四周,看到一些关于线程的提及,但它会有助于看到一个例子,或指向我正确的方向.谢谢. 想在后台运行run_sleep. #!/usr/bin/perlprint "Start of script";run_sleep();print "End of script";sub run_sleep { select(unde
有没有办法在后台运行perl子程序?我环顾四周,看到一些关于线程的提及,但它会有助于看到一个例子,或指向我正确的方向.谢谢.

想在后台运行run_sleep.

#!/usr/bin/perl

print "Start of script";
run_sleep();
print "End of script";

sub run_sleep {
    select(undef,undef,5);  #Sleep for 5 seconds then do whatever
}

解决方法

最简单的方法(恕我直言)是 fork一个子进程让它做的工作. Perl线程可能会很痛苦,所以尽量避免使用它们.

这是一个简单的例子

use strict;
use warnings;

print "Start of scriptn";
run_sleep();
print "End of scriptn";

sub run_sleep { 
    my $pid = fork;
    return if $pid;     # in the parent process
    print "Running child processn";
    select undef,5;
    print "Done with child processn";
    exit;  # end child process
}

如果你在shell中运行它,你会看到如下所示的输出:

Start of script
End of script
Running child process

(等五秒钟)

Done with child process

父进程将立即退出并返回到您的shell;子进程将在五秒后将其输出发送到您的shell.

如果您希望父进程在子进程完成之前保持不变,则可以使用waitpid.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读