如何使用操作系统提供的相关函数来创建、写入和读取管道的代码示例
时间: 2024-05-05 22:19:25 浏览: 10
以下是一个使用操作系统提供的相关函数来创建、写入和读取管道的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
int main() {
int pipefd[2];
pid_t pid;
char buf[256];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
close(pipefd[0]); // Close the read end of the pipe
char *msg = "Hello, parent!";
write(pipefd[1], msg, strlen(msg));
exit(EXIT_SUCCESS);
} else {
// Parent process
close(pipefd[1]); // Close the write end of the pipe
int nbytes = read(pipefd[0], buf, sizeof(buf));
printf("Received message from child: %.*s\n", nbytes, buf);
wait(NULL);
exit(EXIT_SUCCESS);
}
return 0;
}
```
这段代码中,我们先创建了一个长度为 2 的整型数组 `pipefd`,用于存储创建的管道的文件描述符。然后,我们使用 `pipe()` 函数创建了一个管道,将读端的文件描述符存储在 `pipefd[0]` 中,将写端的文件描述符存储在 `pipefd[1]` 中。
接着,我们创建了一个子进程,并使用 `fork()` 函数进行了复制。在子进程中,我们关闭了读端的文件描述符,然后向写端写入了一条消息。在父进程中,我们关闭了写端的文件描述符,然后读取了从管道中接收到的消息,并输出到控制台上。
需要注意的是,我们调用了 `wait()` 函数,以等待子进程的结束。如果不调用该函数,父进程将在子进程结束前就退出,导致管道中的数据无法完整地被读取到。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)