如何从父进程向子进程发送消息(或信号),反之亦然?
我正在编写一个管理多重过程的程序。这就是我所做的,它的工作很棒!但现在,我想从子进程发送消息到父进程,反之亦然(从父进程到子进程),你知道最好的方法吗?你知道我所做的是否是我想要的正确方法(发送消息,信号或从子进程共享内存到父进程,反之亦然)?
提前致谢!!
#!/usr/bin/perl -w
use strict;
use warnings;
main(@ARGV);
sub main{
my $num = 3; #this may change in the future (it would be dynamic)
my @parts = (1,4,9,17,23,31,46,50);
my @childs = ();
while(scalar(@parts)>0 || scalar(@childs)>0){
if(scalar(@parts)>0){
my $start = scalar(@childs) + 1;
for($start..$num){
my $partId = pop(@parts);
my $pid = fork();
if ($pid) {
print "Im going to wait (Im the parent); my child is: $pid. The part Im going to use is: $partId n";
push(@childs, $pid);
}
elsif ($pid == 0) {
my $slp = 5 * $_;
print "$_ : Im going to execute my code (Im a child) and Im going to wait like $slp seconds. The part Im going to use is: $partIdn";
sleep $slp;
print "$_ : I finished my sleepn";
exit($slp);
}
else{
die "couldn’t fork: $!n";
}
}
}
print "before retn";
my $ret = wait();
print "after ret. The pid=$retn";
my $index = 0;
for my $value (@childs){
if($value == $ret) {
splice @childs, $index, 1;
last;
}
$index++;
}
}
}
没有找到相关结果
已邀请:
2 个回复
马口
有关kill call的更多详细信息,请参阅
如果您需要做更复杂的事情,另一个选择是使用POE
枫湃揩乾纲
具有良好的接口,用于在父进程和子进程之间传递消息(进程间通信)。使用此接口,您可以将消息传递给子节点的STDIN,并从子节点的STDOUT和STDERR句柄中读取消息。