我已經創建了一個爲父進程創建兩個子進程的程序。該程序將輸出顯示其進程ID的父進程,然後輸出顯示其ID和父進程ID的兩個子進程。在程序退出並打印輸出後,父進程應該使用wait()
函數來捕獲子進程。創建過多的進程,似乎只能終止父進程
但是,我的程序不斷創建父進程並給這些進程提供子進程。我只需要一個父進程來處理兩個子進程。在while循環內部是wait()
函數,該函數應該檢查子進程的更改狀態並打印「Child'xxx'進程已終止」。相反,它正在終止一些父進程和其他隨機進程。
#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);
}
我的輸出顯示我這個
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();」 –