From 63a0e730096e71c7ce99a14d80727c704b55e2d3 Mon Sep 17 00:00:00 2001 From: flykhan Date: Wed, 16 Aug 2023 10:34:26 +0800 Subject: [PATCH] =?UTF-8?q?day2:=20=E4=BD=9C=E4=B8=9A8=20=E5=86=99?= =?UTF-8?q?=E6=B3=95=E4=BA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day2/homework/h8_2.c | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 day2/homework/h8_2.c diff --git a/day2/homework/h8_2.c b/day2/homework/h8_2.c new file mode 100644 index 0000000..f694acc --- /dev/null +++ b/day2/homework/h8_2.c @@ -0,0 +1,39 @@ +// 请分析如下程序,如何实现创建2个子进程, 第一个子进程输出ABC, 第二子进程输出 DEF。 +// 做法二 +#include +#include +#include +#include + +int main(int argc, char *argv[]) +{ + // 创建2个子进程 + int i; + for (i = 0; i < 2; i++) + { + pid_t pid = fork(); + if (pid == 0) + { + if (i == 0) + printf("%d ABC\n", getpid()); + + else + printf("%d DEF\n", getpid()); + + _exit(0); + } + } + + // 等待所有子进程结束 + while (1) + { + // 等待任意子进程结束,并获取已终止子进程的进程ID + int pid = waitpid(-1, NULL, WUNTRACED); // -1 表示等待任意子进程 + printf("子进程 %d over\n", pid); + if (pid == -1) + break; + } + printf("主进程 %d over\n", getpid()); + + return 0; +}