加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl子进程给父进程传数据

发布时间:2020-12-16 00:37:49 所属栏目:大数据 来源:网络整理
导读:pipe (FROM_PARENT,TO_CHILD) or die " pipe : $!"; pipe (FROM_CHILD,TO_PARENT) or die " pipe :$!"; select (( select (TO_CHILD),$| = 1))[0]); # 自动刷新 select (( select (TO_PARENT),$| = 1))[0]); # 自动刷新 if ($pid = fork ) { close FROM_PARE
pipe(FROM_PARENT,TO_CHILD)   or die "pipe: $!";
pipe(FROM_CHILD,TO_PARENT)   or die "pipe:$!";
select((select(TO_CHILD),$| = 1))[0]);      # 自动刷新
select((select(TO_PARENT),$| = 1))[0]);   # 自动刷新

if ($pid = fork) {
        close FROM_PARENT; close TO_PARENT;
        print TO_CHILD "Parent Pid $$ is sending thisn";
        chomp($line = <FROM_CHILD>);
        print "Parent Pid $$ just read this: `$line'n";
        close FROM_CHILD; close TO_CHILD;
        waitpid($pid,0);
} else {
        die "cannot fork: $!" unless defined $pid;
        close FROM_CHILD; close TO_CHILD;
        chomp($line = <FROM_PARENT>);
        print "Child Pid $$ just read this: `$line'n";
        print TO_PARENT "Child Pid $$ is sending thisn";
        close FROM_PARENT; close TO_PARENT;
        exit;
}

?

#!/usr/bin/perl
use strict;
use POSIX ":sys_wait_h";
use Data::Dumper;
my %hash;
print "startn";
my $count=3;


pipe(READER,WRITER) or die "pipe error $!";

while($count--){
??????? my $pid=fork();

??????? if($pid){
??????????????? print "In parentn $$?? -- $pidn";
??????????????? $hash{$pid}=1;
??????? }else{
??????????????? close READER;
??????????????? open(STDOUT,">&WRITER");
??????????????? #sleep 4;
??????????????? srand();
??????????????? my $sltime = 8*rand();
??????????????? sleep $sltime;
??????????????? print "In child $$ return value $sltimen";
??????????????? exit 0;
??????? }

}
close WRITER;


while(scalar(keys(%hash))>0){
??????? sleep 1;
??????? print Dumper %hash;
??????? while ((my $collect = waitpid(-1,WNOHANG)) > 0) {
??????????????? print "$collect exitn";
??????????????? delete $hash{$collect};
??????? }

}

while(<READER>){
??????? print Dumper $_;
}
?

[root@test1 fork]# perl test.pl start In parent ?11359?? -- 11360 In parent ?11359?? -- 11361 In parent ?11359?? -- 11362 $VAR1 = { ????????? '11360' => 1,????????? '11362' => 1,????????? '11361' => 1 ??????? }; 11361 exit 11362 exit $VAR1 = { ????????? '11360' => 1 ??????? }; $VAR1 = { ????????? '11360' => 1 ??????? }; $VAR1 = { ????????? '11360' => 1 ??????? }; $VAR1 = { ????????? '11360' => 1 ??????? }; $VAR1 = { ????????? '11360' => 1 ??????? }; 11360 exit $VAR1 = 'In child 11361 return value 0.727502020665298 '; $VAR1 = 'In child 11362 return value 1.97574310994972 '; $VAR1 = 'In child 11360 return value 6.72100603266884 ';

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读