qfedu-linux-advanced-level/day2/homework/h8.c

50 lines
1.1 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 请分析如下程序如何实现创建2个子进程 第一个子进程输出ABC, 第二子进程输出 DEF。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
// 创建2个子进程
int i;
for (i = 0; i < 2; i++)
{
pid_t pid = fork();
if (pid < 0)
{
perror("fork");
return -1;
}
else if (pid == 0)
{
// 子进程的代码
if (i == 0)
{
// 第一个子进程输出"ABC"
printf("ABC\n");
}
else if (i == 1)
{
// 第二个子进程输出"DEF"
printf("DEF\n");
}
return 0;
}
}
// 等待所有子进程结束
while (1)
{
// 等待任意子进程结束并获取已终止子进程的进程ID
pid_t terminated_pid = wait(NULL);
if (terminated_pid < 0)
{
// 所有子进程都已经结束
break;
}
}
return 0;
}