编写一段程序,使用系统调用 fork( )创建两个子进程。 ⚫ 当此程序运行时,在系统中有一个父进程和两个子进程活动。 ⚫ 让每一个进程在屏幕上显示一个字符:父进程显示'a',子进程分别显示字符'b' 和字符'c'。 ⚫ 试观察记录屏幕上的显示结果,并分析原因。 (2) 修改上述程序,每一个进程循环显示一句话。 ⚫ 子进程显示'daughter ...'及'son ......',父进程显示 'parent ......'。 ⚫ 观察结果,分析原因。
时间: 2023-11-22 08:53:16 浏览: 37
以下是第一问的程序:
```c
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2;
pid1 = fork();
if (pid1 < 0) {
printf("Error: fork failed.\n");
return 1;
} else if (pid1 == 0) {
printf("Child process 1 (PID %d) is running, and it will display 'b'.\n", getpid());
printf("b\n");
} else {
pid2 = fork();
if (pid2 < 0) {
printf("Error: fork failed.\n");
return 1;
} else if (pid2 == 0) {
printf("Child process 2 (PID %d) is running, and it will display 'c'.\n", getpid());
printf("c\n");
} else {
printf("Parent process (PID %d) is running, and it will display 'a'.\n", getpid());
printf("a\n");
}
}
return 0;
}
```
输出结果可能是:
```
Parent process (PID 12345) is running, and it will display 'a'.
a
Child process 2 (PID 12347) is running, and it will display 'c'.
c
Child process 1 (PID 12346) is running, and it will display 'b'.
b
```
这是因为当调用 `fork()` 时,操作系统会复制一份父进程的代码、数据和堆栈等信息,生成一个全新的子进程。子进程与父进程几乎完全相同,但有一些区别。在子进程中,`fork()` 的返回值是0,而在父进程中,`fork()` 的返回值是新创建子进程的进程ID。因此,我们可以通过检查 `fork()` 的返回值来分辨当前进程是父进程还是子进程。
以下是第二问的程序:
```c
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2;
pid1 = fork();
if (pid1 < 0) {
printf("Error: fork failed.\n");
return 1;
} else if (pid1 == 0) {
while (1) {
printf("Daughter process (PID %d) is running.\n", getpid());
printf("daughter ...\n");
sleep(1);
printf("daughter ...\n");
sleep(1);
printf("daughter ...\n");
sleep(1);
}
} else {
pid2 = fork();
if (pid2 < 0) {
printf("Error: fork failed.\n");
return 1;
} else if (pid2 == 0) {
while (1) {
printf("Son process (PID %d) is running.\n", getpid());
printf("son ...\n");
sleep(1);
printf("son ...\n");
sleep(1);
printf("son ...\n");
sleep(1);
}
} else {
while (1) {
printf("Parent process (PID %d) is running.\n", getpid());
printf("parent ...\n");
sleep(1);
}
}
}
return 0;
}
```
输出结果可能是:
```
Parent process (PID 12345) is running.
parent ...
Daughter process (PID 12346) is running.
daughter ...
daughter ...
daughter ...
Son process (PID 12347) is running.
son ...
son ...
son ...
parent ...
son ...
daughter ...
daughter ...
daughter ...
parent ...
son ...
daughter ...
daughter ...
daughter ...
parent ...
son ...
daughter ...
daughter ...
daughter ...
parent ...
son ...
...
```
这是因为在操作系统中,每个进程都有自己的输出缓冲区。当我们调用 `printf()` 函数时,输出的内容首先被写入到缓冲区中,而不是立即显示在屏幕上。当缓冲区被填满或者我们显式地调用 `fflush(stdout)` 函数时,缓冲区中的内容才会被刷新并显示在屏幕上。
在本例中,由于父进程和两个子进程都在不停地输出内容,它们的输出结果可能会交错在一起,产生混乱的效果。为了避免这种情况,我们可以使用 `fflush(stdout)` 函数强制刷新输出缓冲区,或者使用系统调用 `write()` 直接向标准输出文件描述符写入内容,这样可以避免输出缓冲区的影响。