【问题标题】:Introduction to Parents/Childs and Forks Inquiry (Perl)父母/孩子和叉子查询简介(Perl)
【发布时间】: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 感谢您的帮助。暴民奇怪的是坏的,还是奇怪的,为什么它会这样工作?
  • 请注意,在调用子例程时使用显式&amp;前缀是可选的,一般不推荐使用,参见perlsubWhen should I use the & to call a Perl subroutine?
  • 如果你想要当前进程的PID,使用$$

标签: perl fork parent-child


【解决方案1】:

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

分叉

执行 fork(2) 系统调用来创建一个运行 相同的程序在同一点。它将子 pid 返回到 父进程,0 到子进程,或者“undef”,如果 分叉不成功。

fork 之后,$$ 在子进程中被更改为新的进程id。因此子进程可以读取$$ 来获取子进程id(它自己的id)。

【讨论】:

  • 这不准确。 $$ 的值在您检查时更改,而不是在您的 fork 时更改。 $$getpid() 的包装器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 1970-01-01
  • 2011-08-31
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多