编写一段程序,使用系统调用fork()来创建两个子进程,并由父进程重复显示某字符串和自己的标识数,而子进程则重复显示某字符串和自己的标识数
时间: 2023-05-12 16:07:01 浏览: 106
以下是使用系统调用fork()来创建两个子进程,并由父进程重复显示某字符串和自己的标识数,而子进程则重复显示某字符串和自己的标识数的程序:
```c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t pid1, pid2;
int i;
pid1 = fork();
if (pid1 < 0) {
printf("Fork failed!\n");
return 1;
} else if (pid1 == 0) {
// Child process 1
for (i = 0; i < 5; i++) {
printf("Child process 1: %d\n", i);
sleep(1);
}
} else {
pid2 = fork();
if (pid2 < 0) {
printf("Fork failed!\n");
return 1;
} else if (pid2 == 0) {
// Child process 2
for (i = 0; i < 5; i++) {
printf("Child process 2: %d\n", i);
sleep(1);
}
} else {
// Parent process
for (i = 0; i < 5; i++) {
printf("Parent process: %d\n", i);
sleep(1);
}
}
}
return 0;
}
```
请注意,这只是一个示例程序,实际上您可以根据自己的需求进行修改和扩展。