forkとwaitpidを使用したプログラムを次に示します。
#!/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 は、childs が終了するのを待つために使用されます。
私の質問は
子プロセスに対してelseブロックが実行される方法と理由は? フォークが新しい子プロセスを作成したことがわかりました。しかし、fork ステートメントの後で子 (else ブロック) の実行はどのように行われるのでしょうか? 誰かが子プロセスについてこのステップバイステップで説明してくれますか、または子が以下のステートメントを実行しない理由のように、私が見逃しているものについてより多くの洞察を得ることができますか?
print "I AM THE ONLY PROCESS.\n";