如何在分叉进程之间共享相同的变量?或者,我是否需要写入父文件中的文件,然后在文件存在后读取保存到子文件中的值? $something似乎永远不会在此设置,所以它只是在睡眠中循环
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.
参见perldoc perlipc中的Bidirectional Communication with Yourself.
更新:第二个想法,你想要这样的东西吗?
#!/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