c - 具有不同节点的 C (Linux) 中的叉树
问题描述
我在学校学习 C 和 Linux。我的任务是创建看起来像屏幕截图的家庭流程。
[![叉树][1]][1] [1]:https://i.stack.imgur.com/IV5zD.png
我不允许使用 break
. 我在第一行使用了一个 for
循环 int i = 4
,因此父级创建了 4 个子级。我尝试做另一个 for
循环 j < 2
,以便 4 个孩子中的每一个创建 2 个孩子,但是循环创建了太多的孩子,父母不正确......我也尝试过 pid=fork()
,它只创建了 1 个孩子。
你有一个想法,如何到 fork()
第二行,所以 4 个孩子每个创造 2 个孩子?我目前的代码是这样的:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
int main() {
int i,j;
pid_t pid1,pid2;
printf("Parent PID: %d\n", getpid());
for (i = 0; i < 4; i++) {
pid1 = fork();
if (pid1 == -1) {
perror("fork() failure");
return 1;
} else if (pid1 == 0) {
printf("Child: PID: %d; PPID: %d\n", getpid(), getppid());
pid2=fork();
if(pid2==0){
printf("PID: %d of %d\n", getpid(), getppid());
}
return 0;
}
}
}
输出:
Parent PID: 1262
Child: PID: 1263; PPID: 1262
Child: PID: 1264; PPID: 1262
PID: 1265 of 1263
Child: PID: 1266; PPID: 1262
PID: 1267 of 1264
Child: PID: 1268; PPID: 1262
PID: 1269 of 1266
PID: 1270 of 1268
解决方案
推荐阅读
- javascript - 反应js。如何制作具有这种结构的组件:
组件描述 - mysql - mysql 8 MyISAM“显示表状态”行数
- python - 模块崩溃时未处理 Python 异常
- ruby-on-rails - javascript/packs 中的所有 js 文件都没有加载到我的生产应用程序中
- jquery - 具有自定义视图的 JQuery 数据表
- php - 在 Laravel 中通过 $request->validated 传递哈希密码?
- java - 如何在 jOOQ 查询中使用 Postgres 的 to_char?
- python - Python 教程中没有提供 Azure 沙盒的密码
- node.js - 高贵的 BLE 模块-characteristic.subscribe() 命中错误
- reactjs - Material-UI 复选框背景颜色