【发布时间】:2017-07-25 16:41:27
【问题描述】:
我正在尝试学习 perl 中父母、孩子和管道的功能。我的目标是创建一个从命令行读取的单个管道(不是双向的),并通过管道打印它。多次引用pid。
到目前为止的代码:
#!/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。 -
@HåkonHægland 感谢您的帮助。暴民奇怪的是坏的,还是奇怪的,为什么它会这样工作?
-
请注意,在调用子例程时使用显式
&前缀是可选的,一般不推荐使用,参见perlsub和When should I use the & to call a Perl subroutine? -
如果你想要当前进程的PID,使用
$$
标签: perl fork parent-child