gpt4 book ai didi

perl - 在后台运行 perl 子程序

转载 作者:行者123 更新时间:2023-12-04 16:47:40 27 4
gpt4 key购买 nike

有没有办法在后台运行 perl 子程序?我环顾四周,看到了一些关于线程的提及,但看到一个例子会有所帮助,或者为我指明正确的方向。谢谢。

想跑run_sleep在后台。

#!/usr/bin/perl

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

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

最佳答案

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

这是一个简单的例子

use strict;
use warnings;

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

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

如果您在 shell 中运行它,您将看到如下所示的输出:
Start of script
End of script
Running child process

(等待五秒钟)
Done with child process

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

如果您希望父进程一直存在直到子进程完成,那么您可以使用 waitpid .

关于perl - 在后台运行 perl 子程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13925825/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com