#!/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";