如何在分叉进程之间共享相同的变量?或者,我是否需要写入父文件中的文件,然后在文件存在后读取保存到子文件中的值? $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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。