【问题标题】:Why is else block executed for child process?为什么要为子进程执行 else 块?
【发布时间】:2013-01-20 11:50:53
【问题描述】:

这是一个包含forkwaitpid 的程序。

#!/usr/bin/perl
use strict;
use warnings;
my ($childProcessID, $i);

print "I AM THE ONLY PROCESS.\n";

$childProcessID = fork ();

if ($childProcessID){
        print "I am the parent process.\n";
        print "I spawned a new process with ID $childProcessID\n";
        waitpid ($childProcessID, 0);
        print "The child process is terminated with status $?\n";
    }
else{
    for ($i = 0; $i <= 10; $i++){
         print "I am the child process: Counting $i\n";
    }
}

输出可能如下所示。

I AM THE ONLY PROCESS.
I am the parent process.
I spawned a new process with ID 7610
I am the child process: Counting 0
I am the child process: Counting 1
I am the child process: Counting 2
I am the child process: Counting 3
I am the child process: Counting 4
I am the child process: Counting 5
I am the child process: Counting 6
I am the child process: Counting 7
I am the child process: Counting 8
I am the child process: Counting 9
I am the child process: Counting 10
The child process is terminated with status 0

现在有很多关于fork 在网络和书籍中的类似程序,也就是说

if 块中的代码由父进程执行,else 中的代码由子进程执行。 waitpid 用于等待孩子完成。

我的问题是

else 块如何以及为什么为子进程执行? 我知道 fork 已经创建了新的子进程。但是在 fork 语句之后如何执行 child(即 else 块)?有人可以逐步向我解释子进程,或者更深入地了解我缺少的东西,例如为什么子进程不执行下面的语句?

print "I AM THE ONLY PROCESS.\n";

【问题讨论】:

    标签: perl process fork child-process waitpid


    【解决方案1】:

    Fork 在执行时将当前进程分成两个。两个进程在 fork 调用之后继续执行。

    两个结果进程之间唯一的*区别在于,在一个(父进程)中,fork() 返回子进程的 PID,而在另一个进程(子进程)中,fork() 返回零.

    因此,在父级中,$childProcessID 非零并采用if 分支,而在子级中该变量为零并执行else 分支。

    * 可能不是真的学究气。

    【讨论】:

    • fork() 在子级中返回零。行。那么如果我在第一个 fork 语句之后再说一个 fork() 怎么办。那么对于孩子和父母来说,都会有孩子,是吗?
    • 是的,如果你的程序执行fork(); fork(); print "foo\n",就会有四个进程在运行打印语句。
    猜你喜欢
    • 1970-01-01
    • 2019-05-12
    • 2015-02-12
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    相关资源
    最近更新 更多