如何使用 Fork() 只创建 2 个子进程? [英] How to use Fork() to create only 2 child processes?
问题描述
我开始学习一些 C 语言,在学习 fork、wait 函数时,我得到了一个意想不到的输出.至少对我来说.
I'm starting to learn some C and while studying the fork, wait functions I got to a unexpected output. At least for me.
有没有办法只从父进程创建 2 个子进程?
Is there any way to create only 2 child processes from the parent?
这是我的代码:
#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
");
return -1;
}
else if (pid == 0)
{
//printf("I'm the child
");
}
else
{
//printf("I'm the parent
");
}
printf("I'm pid %d
",getpid());
return 0;
}
这是我的输出:
I'm pid 6763
I'm pid 6765
I'm pid 6764
I'm pid 6766
请忽略管道部分,我还没有达到那个程度.我只是想只创建 2 个子进程,所以我希望 3 个我是 pid ..."只为父进程输出 1 个我将等待的父进程和 2 个将通过管道进行通信的子进程.
Please, ignore the pipe part, I haven't gotten that far yet. I'm just trying to create only 2 child processes so I expect 3 "I'm pid ..." outputs only 1 for the parent which I will make wait and 2 child processes that will communicate through a pipe.
如果你看到我的错误在哪里,请告诉我.
Let me know if you see where my error is.
推荐答案
pid = fork (); #1
pidb = fork (); #2
让我们假设父进程 id 是 100,第一个 fork 创建另一个进程 101.现在 100 &101在#1之后继续执行,所以他们执行第二个fork.pid 100 到达 #2 创建另一个进程 102.pid 101 到达 #2 创建另一个进程 103.所以我们最终有 4 个进程.
Let us assume the parent process id is 100, the first fork creates another process 101. Now both 100 & 101 continue execution after #1, so they execute second fork. pid 100 reaches #2 creating another process 102. pid 101 reaches #2 creating another process 103. So we end up with 4 processes.
你应该做的是这样的事情.
What you should do is something like this.
if(fork()) # parent
if(fork()) #parent
else # child2
else #child1
这篇关于如何使用 Fork() 只创建 2 个子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!