windows编写一段程序,使用系统调用 fork0来创建两个子进程,并由父进程重复显示字符串“parent:”和自己的标识数,子进程则重复显示字符串“child:”和自己的标识数
时间: 2024-05-02 20:18:53 浏览: 19
以下是一个使用系统调用 fork() 来创建两个子进程,并由父进程重复显示字符串“parent:”和自己的标识数,子进程则重复显示字符串“child:”和自己的标识数的示例程序:
```c
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t child1, child2;
int status;
// 创建第一个子进程
child1 = fork();
if (child1 == -1) {
printf("Failed to create child1.\n");
return 1;
} else if (child1 == 0) {
// 子进程1
printf("child1: %d\n", getpid());
return 0;
}
// 创建第二个子进程
child2 = fork();
if (child2 == -1) {
printf("Failed to create child2.\n");
return 1;
} else if (child2 == 0) {
// 子进程2
printf("child2: %d\n", getpid());
return 0;
}
// 父进程
printf("parent: %d\n", getpid());
// 等待子进程结束
waitpid(child1, &status, 0);
waitpid(child2, &status, 0);
return 0;
}
```
在上面的程序中,我们先创建了第一个子进程 child1,然后再创建第二个子进程 child2。在每个子进程中,我们简单地输出了进程的 PID。在父进程中,我们输出了父进程的 PID。最后,我们使用 waitpid() 函数来等待两个子进程的结束。
注意,fork() 函数会返回两次,一次在父进程中,一次在子进程中。因此,我们需要在程序中使用条件语句来判断当前进程是父进程还是子进程。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)