任何人都可以解释我如何成功地让我的流程进行沟通吗?我发现IPC上的perldoc令人困惑。
到目前为止我所拥有的是:
$| = 1;
$SIG{CHLD} = {wait};
my $parentPid = $$;
if ($pid = fork();) ) {
if ($pid == 0) {
pipe($parentPid, $$);
open PARENT, "<$parentPid";
while (<PARENT>) {
print $_;
}
close PARENT;
exit();
} else {
pipe($parentPid, $pid);
open CHILD, ">$pid";
or error("\nError opening: childPid\nRef: $!\n");
open (FH, "<list")
or error("\nError opening: list\nRef: $!\n");
while(<FH>) {
print CHILD, $_;
}
close FH
or error("\nError closing: list\nRef: $!\n");
close CHILD
or error("\nError closing: childPid\nRef: $!\n);
} else {
error("\nError forking\nRef: $!\n");
}
首先:READHANDLE
对WRITEHANDLE
,{{1}}的含义是什么?
第二:我可以在不依赖CPAN或其他模块的情况下实施解决方案吗?
答案 0 :(得分:5)
以下是基于perldoc perlipc中的代码的简化示例:
#!/usr/bin/perl
use strict; use warnings;
$SIG{CHLD} = sub { wait };
pipe my $reader, my $writer;
my $pid = fork;
defined $pid or die "fork failed: $!";
if ( $pid ) { # parent
close $reader;
for my $n ( 1 .. 5 ) {
select $writer;
$| = 1;
print $writer "Message $n\n"
or die "Failed to pass message to child: $!";
sleep 1;
}
close $writer;
exit;
}
else { # child
close $writer;
while ( my $msg = <$reader> ) {
print "Child received: $msg";
last if rand > 0.5; # to check error handling in parent
}
close $reader;
exit;
}