![](/img/trans.png)
[英]Use Fork() to create three child processes with only 2 grandchild processes
[英]How to use Fork() to create only 2 child processes?
我開始學習一些C並且在研究fork時,等待函數我得到了意想不到的輸出。 至少對於我來說。
有沒有辦法從父級創建只有2個子進程?
這是我的代碼:
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main ()
{
/* Create the pipe */
int fd [2];
pipe(fd);
pid_t pid;
pid_t pidb;
pid = fork ();
pidb = fork ();
if (pid < 0)
{
printf ("Fork Failed\n");
return -1;
}
else if (pid == 0)
{
//printf("I'm the child\n");
}
else
{
//printf("I'm the parent\n");
}
printf("I'm pid %d\n",getpid());
return 0;
}
這是我的輸出:
I'm pid 6763
I'm pid 6765
I'm pid 6764
I'm pid 6766
請忽略管道部分,我還沒有那么遠。 我只是想創建只有2個子進程,所以我希望3“我是pid ......”只輸出1個父級,我將等待,2個子進程將通過管道進行通信。
如果你看到我的錯誤在哪里,請告訴我。
pid = fork (); #1
pidb = fork (); #2
讓我們假設父進程id為100,第一個fork創建另一個進程101.現在100和101都在#1之后繼續執行,因此它們執行第二個fork。 pid 100到達#2,創建另一個進程102.pid 101到達#2,創建另一個進程103.所以我們最終得到4個進程。
你應該做的是這樣的事情。
if(fork()) # parent
if(fork()) #parent
else # child2
else #child1
創建進程后,應檢查返回值。 如果不這樣做,則seconde fork()
將由父進程和子進程執行,因此您有四個進程。
如果你想創建2個子進程,只需:
if (pid = fork()) {
if (pid = fork()) {
;
}
}
你可以像這樣創建n個子進程:
for (i = 0; i < n; ++i) {
pid = fork();
if (pid > 0) { /* I am the parent, create more children */
continue;
} else if (pid == 0) { /* I am a child, get to work */
break;
} else {
printf("fork error\n");
exit(1);
}
}
當父語句執行fork語句時,會按照您的預期創建子進程。 您可以說子進程也執行fork語句但返回0,但父進程返回pid。 fork語句之后的所有代碼都由父級和子級執行。
在你的情況下,發生的事情是第一個fork語句創建了一個子進程。 所以現在有一個父母P1和一個孩子C1。
現在P1和C1都遇到第二個fork語句。 父母會按照您的預期創建另一個孩子(c2),但即使是孩子,c1也會創建一個子進程(c3)。 所以實際上你有P1,C1,C2和C3,這就是你有4個打印語句輸出的原因。
考慮這個的一個好方法是使用樹,每個節點代表一個進程,根節點是最頂層的父節點。
您可以檢查值,如果(pid <0)進程創建失敗,這告訴子進程創建是否不成功。如果從父進程使用getpid(),fork將返回子進程的進程ID。
您可以在子進程中創建子進程。 這樣,您可以擁有原始父進程的2個副本。
int main (void) {
pid_t pid, pid2;
int status;
pid = fork();
if (pid == 0) { //child process
pid2 = fork();
int status2;
if (pid2 == 0) { //child of child process
printf("friends!\n");
}
else {
printf("my ");
fflush(stdout);
wait(&status2);
}
}
else { //parent process
printf("Hello ");
fflush(stdout);
wait(&status);
}
return 0;
}
這打印出以下內容:
Hello my friends!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.