编写一段程序,使用系统调用fork ( )创建两个子进程,使系统中有一个父进程和两个子进程活动,让每一个进程循环十次,每次sleep( )特定不同时间(三个进程各选择不同时间),再在屏幕上输出带循环次数的字符串。
时间: 2023-06-01 07:01:39 浏览: 146
以下是使用fork()创建两个子进程的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2;
int i;
pid1 = fork(); // 创建第一个子进程
if (pid1 < 0) {
perror("fork error");
exit(EXIT_FAILURE);
} else if (pid1 == 0) {
// 子进程1
for (i = 0; i < 10; i++) {
sleep(1);
printf("Child process 1: loop %d\n", i + 1);
}
exit(EXIT_SUCCESS);
} else {
pid2 = fork(); // 创建第二个子进程
if (pid2 < 0) {
perror("fork error");
exit(EXIT_FAILURE);
} else if (pid2 == 0) {
// 子进程2
for (i = 0; i < 10; i++) {
sleep(2);
printf("Child process 2: loop %d\n", i + 1);
}
exit(EXIT_SUCCESS);
} else {
// 父进程
for (i = 0; i < 10; i++) {
sleep(3);
printf("Parent process: loop %d\n", i + 1);
}
exit(EXIT_SUCCESS);
}
}
}
```
在上面的程序中,我们使用了fork()函数创建了两个子进程,并在每个进程中循环了10次。每个进程使用了不同的睡眠时间来模拟不同的活动。最后,我们在每个进程循环时输出了带循环次数的字符串。
请注意,父进程和子进程的代码是分开的,并且我们使用了exit()函数来在进程结束时退出。此外,我们还使用了perror()函数来在出现错误时输出错误信息。