2017-03-05 65 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