gpt4 book ai didi

perl - 我如何向 fork 的 child 发出信号以终止在 Perl 中?

转载 作者:行者123 更新时间:2023-12-04 21:55:10 24 4
gpt4 key购买 nike

如何在 fork 进程之间共享相同的变量?或者我是否需要写入父文件中的文件,然后在文件存在后读取保存到子文件中的值? $something 似乎从未在此设置,因此它只是在 sleep 中循环

my $something = -1;
&doit();
sub doit
{

my $pid = fork();
if ($pid == 0)
{
while ($something == -1)
{
print "sleep 1\n";
sleep 1;
}
&function2();
}
else
{
print "parent start\n";
sleep 2;
$something = 1;
print "parent end: $something\n";
}
}

sub function2 {
print "END\n";
}

最佳答案

perldoc -f fork :

File descriptors (and sometimes locks on those descriptors) are shared, while everything else is copied.



另见 Bidirectional Communication with Yourselfperldoc perlipc .

更新:转念一想,你想要这样的东西吗?
#!/usr/bin/perl

use strict;
use warnings;

my $pid = fork;

die "Cannot fork: $!" unless defined $pid;

if ($pid == 0) {
print "Child start\n";
my $end;
local $SIG{HUP} = sub { $end = 1 };

until ($end) {
print "Sleep 1\n";
sleep 1;
}
function2();
}
else {
print "Parent start\n";
sleep 5;
kill HUP => $pid;
waitpid($pid, 0);
}

sub function2 {
print "END\n";
}

输出:
C:\Temp> w
Parent start
Child start
Sleep 1
Sleep 1
Sleep 1
Sleep 1
Sleep 1
END

关于perl - 我如何向 fork 的 child 发出信号以终止在 Perl 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1260639/

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