我正在嘗試學習父母,孩子和管道在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感謝您的支持。怪怪的不好,或者怪怪的,爲什麼它以這種方式工作? –