编写一段程序,使用系统调用fork ( )创建两个子进程。当此程序运行时,在系统中有一个父进程和两个子进程活动。让每一个进程在屏幕上显示一个字符:父进程显示字符“a”;子进程显示字符“b”和字符“c”。试观察记录屏幕上的显示结果,并分析原因。
时间: 2024-05-19 21:17:23 浏览: 11
答案:
可以使用以下程序:
#include<stdio.h>
#include<unistd.h>
int main(void)
{
pid_t pid1, pid2;
pid1 = fork();
if (pid1 < 0)
{
printf("fork error.\n");
return 1;
}
else if (pid1 == 0)
{
printf("Child process 1 (pid:%d) is running. It will show 'b'.\n", getpid());
printf("b\n");
}
else
{
pid2 = fork();
if (pid2 < 0)
{
printf("fork error.\n");
return 1;
}
else if (pid2 == 0)
{
printf("Child process 2 (pid:%d) is running. It will show 'c'.\n", getpid());
printf("c\n");
}
else
{
printf("Parent process (pid:%d) is running. It will show 'a'.\n", getpid());
printf("a\n");
}
}
return 0;
}
在程序中,我们先使用fork()创建了两个子进程,然后根据返回的pid值不同,分别让父进程、子进程1和子进程2显示不同的字符。
运行程序后,可能会得到以下结果:
Parent process (pid:3865) is running. It will show 'a'.
a
Child process 2 (pid:3867) is running. It will show 'c'.
c
Child process 1 (pid:3866) is running. It will show 'b'.
b
可以看到,父进程先输出了自己的字符“a”,然后子进程2输出了“c”,子进程1最后输出了“b”。
原因是fork()调用后,会复制当前进程的代码段、数据段、堆栈段等信息到新的进程空间中,新的进程与原进程几乎完全相同,但pid不同。所以在父进程、子进程1、子进程2三个进程中分别输出了自己的字符。
注意:程序中使用了三个printf函数,因此不同进程的输出顺序可能会有所不同,不同的操作系统和编译器环境也可能会产生不同的结果,因此输出结果可能会有所不同。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)