Linux/Code/jincheng2.c
2025-05-27 16:41:18 +08:00

52 lines
1.0 KiB
C
Raw 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.

/**********************************************
创建一个子进程打印hello后父进程打印world之后父进程再创建两条进程一个进程打印end另一个进程打印...
**********************************************/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
// 创建子进程
pid_t pid = fork();
// 错误处理
if (pid < 0)
{
printf("创建子进程失败\n");
return -1;
}
// 子进程
else if (pid == 0)
{
printf("hello\n");
}
// 父进程
else
{
wait(NULL); // 等待子进程结束
printf("world\n");
// 创建两个新的子进程
pid_t pid1 = fork();
if (pid1 == 0)
{
printf("end\n");
}
else
{
pid_t pid2 = fork();
if (pid2 == 0)
{
printf("...\n");
}
}
}
return 0; // 程序结束
}