我已经一遍又一遍地对此进行编程,并且在学习如何使用 fork() 以便递归生成子进程时遇到了困难。我开始编写一些非常复杂的东西,然后我决定用更简单的东西重新开始。
我刚刚开始学习流程,但在理解它们方面遇到了困难。该程序旨在分叉一棵进程树,但是,我必须从根部分叉两个进程,这两个进程将分叉,在左侧 3 个子进程,在右侧 4 个子进程。这些进程必须分别派生 3 个和 4 个自己的进程。
我的问题是,程序可以分叉进程,但是每一侧只有一个进程是其各自一侧的所有子进程的父进程。
您能给我的任何帮助都会很棒,如果我不够清楚,请告诉我。
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
/* Prototypes */
void three_children();
void four_children();
int main()
{
pid_t process;
int status,n;
printf("Number of levels: \n");
scanf("%d", &n);
for (int i = 0; i < n ; i++) {
process = fork();
switch (process) {
case -1:
printf("Error\n");
break;
case 0:
if (i == 0) {
printf("Left\n");
three_children(process, status);
}
if (i …Run Code Online (Sandbox Code Playgroud)