[英]Perl creating a pipe and fork a sub-process
我在這里試圖做的是:
到目前為止,這就是我所得到的:我仍然需要實現一個循環以重復執行,直到用戶不輸入消息為止。
#!perl -w
use strict
pipe(PIPE_READ, PIPE_WRITE);
autoflush PIPE_WRITE 1;
my $pid = fork();
if ($pid) {
&write_pipe ($pid);
waitpid($pid,0);
}
elsif (defined $pid) {
&read_pipe;
}
else {
die "cannot fork: $!";
}
sub write_pipe {
print "pid $$ \n";
print "Enter message: ";
sleep 1;
my $usr_msg = <>;
print "Parent pid = $$ message = $usr_msg";
print PIPE_WRITE "$usr_msg\n";
close(PIPE_WRITE)
close(PIPE_READ);
}
sub read_pipe {
print "child pid = $pid";
my $msg_read = <PIPE_READ>;
close(PIPE_WRITE);
print "received from pipe $msg_read";
}
首先,您無意中創建了兩個孩子。 更換
if ($pid = fork)
與
if ($pid)
在孩子里,打電話
close(PIPE_WRITE);
在家長中,致電
close(PIPE_READ);
在家長(寫完后)中,打電話給
close(PIPE_WRITE);
至於從文件句柄讀取直到輸入EOF或特定命令,
while (my $line = <>) {
last if $line =~ /^(?:quit|exit)$/;
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.