我正在尝试学习父母,孩子和管道在perl中的功能。我的目标是创建一个从命令行读取并通过管道打印的管道(不是双向的)。多次参考pid。父母/孩子和叉子查询介绍(Perl)
至今代码:
#!/usr/bin/perl -w
use warnings;
use strict;
pipe(READPIPE, WRITEPIPE);
WRITEPIPE->autoflush(1);
my $parent = $$;
my $childpid = fork() // die "Fork Failed $!\n";
# This is the parent
if ($childpid) {
&parent ($childpid);
waitpid ($childpid,0);
close READPIPE;
exit;
}
# This is the child
elsif (defined $childpid) {
&child ($parent);
close WRITEPIPE;
}
else {
}
sub parent {
print "The parent pid is: ",$parent, " and the message being received is:", $ARGV[0],"\n";
print WRITEPIPE "$ARGV[0]\n";
print "My parent pid is: $parent\n";
print "My child pid is: $childpid\n";
}
sub child {
print "The child pid is: ",$childpid, "\n";
my $line = <READPIPE>;
print "I got this line from the pipe: $line and the child pid is $childpid \n";
}
的电流输出为:
perl lab5.2.pl "I am brain dead"
The parent pid is: 6779 and the message being recieved is:I am brain dead
My parent pid is: 6779
My child pid is: 6780
The child pid is: 0
I got this line from the pipe: I am brain dead
and the child pid is 0
我试图找出为什么在孩子子程序childpid正在恢复为0,但在父它引用“精确查找”pid#。 是应该返回0吗? (例如,如果我做了多个子程序,他们会是0,1,2等等?)
谢谢先进的。
'$ childpid'由于设置为'fork()'的返回值而在子节点为零。 –
父节点写入'WRITEPIPE'但关闭'READPIPE'并且孩子从' READPIPE“,但关闭了”WRITEPIPE“。 – mob
@HåkonHægland感谢您的支持。怪怪的不好,或者怪怪的,为什么它以这种方式工作? –