2017-03-05 68 views
1

我正在尝试学习父母,孩子和管道在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等等?)

谢谢先进的。

+0

'$ childpid'由于设置为'fork()'的返回值而在子节点为零。 –

+0

父节点写入'WRITEPIPE'但关闭'READPIPE'并且孩子从' READPIPE“,但关闭了”WRITEPIPE“。 – mob

+0

@HåkonHægland感谢您的支持。怪怪的不好,或者怪怪的,为什么它以这种方式工作? –

回答

2

是的,it should be 0,并且它将在来自fork调用的每个子进程中为0。

是否一个叉(2)系统调用来创建运行在相同点处的相同 程序的新方法。它返回父进程的 ,子进程返回0,或者如果 分支不成功,则返回“undef”。

后叉,$$在子进程中更改为新的进程ID。所以孩子可以读取$$来获取子进程ID(自己的ID)。

+0

这并不准确。 '$$'的值在您检查时会发生变化,而不会在'fork'时发生。 '$$'是'getpid()'的封装 – ikegami