我试图创建进程的二叉树结构,其中每个进程不超过 2 个子进程



我试图为每个进程(二叉树)创建两个子进程,如果n=3,进程树结构应该像(1)->(2),(1)->(3),(2)->(4),(2)->(5)。我编写了一个程序,我可以为每个子进程创建 2 个进程,但我想提供一个数字 n=number 并根据以二叉树格式传递的数字创建进程。 这是我的代码:

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>

int foo(const char *whoami) {
printf("I am a %s.  My pid is:%d  my ppid is %dn", whoami, getpid(), getppid() );
return 1;
}
int func() 
{
int pid = fork(); 
if (pid==0) { 
foo("child");
int pid2 = fork(); 
if (pid2==0) { 
foo("child");

exit(0);
}
else {
wait(NULL);
} 
int pid3 = fork(); 
if (pid3==0) { 
foo("child");

exit(0);
}
else {
wait(NULL);
} 
exit(0);
}
else {
wait(NULL);
} 
int pid1 = fork(); 
if (pid1==0) { 
foo("child1");
int pid4 = fork(); 
if (pid4==0) { 
foo("child");

exit(0);
}
else {
wait(NULL);
} 
int pid5 = fork(); 
if (pid5==0) { 
foo("child");

exit(0);
}
else {
wait(NULL);
} 
exit(0);
}
else {
wait(NULL);
} 
return 0;   
}

int main()
{
foo("parent");
func(); 
return 0;
}
output : 

我是父母。 我的 pid 是:37 我的 ppid 是 18
我是个孩子1。 我的 pid 是:38 我的 ppid 是 37
我是一个孩子2。 我的 pid 是:39 我的 ppid 是 38
我是一个孩子3。 我的 pid 是:40 我的 ppid 是 38
我是个孩子4。 我的 pid 是:41 我的 ppid 是 37
我是个孩子。 我的 pid 是:42 我的 ppid 是 41
我是个孩子5。 我的 pid 是:43 我的 ppid 是 41

由于我假设 Raj 理解fork()wait()但还没有理解二叉树的概念(以及如何使用递归函数实现它们),我为此做了一个小的完整示例。它防止使用fork()使二叉树/递归概念更加清晰。

总而言之:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
void foo()
{
printf("child process %d, (%d)->(%d)n",
getpid(), getppid(), getpid());
}
/* creates child processes in binary tree manner.
*
* n ... number of tree nodes (child processes) to create
*/
void do_fork(int n)
{
if (n <= 0) return;
int n1 = n / 2;
int n2 = n - n1;
int pid1 = 0, pid2 = 0;
if (n1 >= 0) {
--n1;
pid1 = fork();
if (pid1 < 0) {
fprintf(stderr, "ERROR: fork failed in process %d!n", getpid());
return;
}
if (pid1 == 0) { 
foo();
do_fork(n1);
exit(0);
}
}
if (n2 >= 0) {
--n2;
pid2 = fork();
if (pid2 < 0) {
fprintf(stderr, "ERROR: fork failed in process %d!n", getpid());
return;
}
if (pid2 == 0) {
foo();
do_fork(n2);
exit(0);
}
}
wait(NULL);
}
int main(int argc, char **argv)
{
int n = 3; /* number of binary tree nodes, might become input */
printf("parent process %d, children to create: %dn", getpid(), n);
if (n) do_fork(n);
return 0;
}

我在cygwin上用gcc编译并测试了它:

$ gcc -o test-bin-tree-fork test-bin-tree-fork.c
$ ./test-bin-tree-fork.exe
parent process 8628, children to create: 3
child process 13608, (8628)->(13608)
child process 7292, (8628)->(7292)
child process 8920, (7292)->(8920)
child process 14104, (7292)->(14104)

最新更新