親プロセスの2つの子プロセスを作成するプログラムを作成しました。このプログラムはプロセスIDを示す親のプロセスを出力し、次にそのIDと親のIDを示す2つの子プロセスを出力します。親プロセスは、プログラムが終了して出力を出力した後に、wait()
関数を使用して子プロセスを取得することになっています。あまりにも多くのプロセスを作成して親プロセスのみを終了するようです
ただし、私のプログラムは親プロセスの作成と子プロセスの保持を続けます。私は、2つの子プロセスに対して1つの親プロセスしか必要としません。 whileループの内部では、子プロセスの変更された状態をチェックし、 "Child 'xxx' process terminated"を印刷すると想定されるwait()
関数があります。代わりに、親プロセスやその他のランダムプロセスのいくつかを終了しています。
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
pid_t cpid, cpid2, wpid;
int child = fork();
int child2 = fork();
int status;
if ((child = fork()) == 0){
child = cpid;
}
if((child2 = fork()) == 0){
child2 = cpid2;
}
else{
printf("I am the parent %d\n", getppid());
printf("I am the process %d created by %d\n", cpid, getppid());
printf("I am the process %d created by %d\n", cpid2, getppid());
while ((wpid = wait(&status)) > 0){
printf("Child process %d terminated\n", wpid);
}
}
return (0);
}
あなたfork()
たら私の出力は、子と親の両方が、あなたが唯一の親プロセスでfork()
を呼び出したい場合は、戻り値をチェックし、再びfork()
を呼び出している、私にこの
I am the parent 5764
I am the process 2 created by 5764
I am the process 6411548 created by 5764
I am the parent 13720
I am the process 2 created by 13720
I am the process 6411548 created by 13720
I am the parent 23612
I am the process 2 created by 23612
I am the process 6411548 created by 23612
I am the parent 15096
I am the process 2 created by 15096
I am the process 6411548 created by 15096
I am the parent 24276
I am the process 2 created by 24276
I am the process 6411548 created by 24276
I am the parent 13720
I am the process 2 created by 13720
I am the process 6411548 created by 13720
I am the parent 13720
I am the process 2 created by 13720
I am the process 6411548 created by 13720
I am the parent 5764
I am the process 2 created by 5764
I am the process 6411548 created by 5764
Child process 17016 terminated
Child process 18584 terminated
Child process 13984 terminated
Child process 8480 terminated
Child process 10816 terminated
Child process 21968 terminated
Child process 23388 terminated
Child process 11452 terminated
Child process 2776 terminated
Child process 19328 terminated
Child process 17116 terminated
Child process 18352 terminated
Child process 24276 terminated
Child process 15096 terminated
Child process 5764 terminated
最初のフォークの親と子の両方が残りのプログラムを実行し続けることを許可しています。彼らは*両方とも*フォークをもう一度進めます。 –
'cpid'と' cpid2'は使用時に未定義です – Tibrogargan
"fork"の呼び出しを削除します "int child = fork(); int child2 = fork();" –