首页 文章

为什么要为子进程执行else块?

提问于
浏览
0

这是一个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用于等待孩子完成 .

我的问题是

How and why is else block executed for child process? 我得到了这个fork创建了新的子进程 . 但是如何在fork语句之后执行child(即else block)的执行?有人可以一步一步地向我解释儿童过程,或者更深入地了解一些我不知道的事情,比如为什么孩子不执行下面的陈述?

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

1 回答

  • 4

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

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

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

    *可能不是真的很迂腐 .

相关问题