c++实现管道代码
时间: 2023-08-06 07:18:23 浏览: 57
以下是 C++ 实现管道的示例代码:
```c++
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
int main() {
int fd[2]; // 定义管道
pid_t pid; // 定义进程 ID
char buf[1024]; // 定义缓冲区
// 创建管道
if (pipe(fd) == -1) {
cout << "Create pipe failed!" << endl;
return -1;
}
// 创建子进程
if ((pid = fork()) == -1) {
cout << "Create child process failed!" << endl;
return -1;
} else if (pid == 0) { // 子进程
close(fd[1]); // 关闭写端
read(fd[0], buf, sizeof(buf)); // 从管道中读取数据
cout << "Child process received message: " << buf << endl;
close(fd[0]); // 关闭读端
} else { // 父进程
close(fd[0]); // 关闭读端
write(fd[1], "Hello, pipe!", sizeof("Hello, pipe!")); // 向管道中写入数据
wait(NULL); // 等待子进程执行完毕
close(fd[1]); // 关闭写端
}
return 0;
}
```
该示例代码中,使用 `pipe` 函数创建了一个管道,然后使用 `fork` 函数创建了一个子进程。在子进程中,关闭了管道的写端,通过 `read` 函数从管道中读取数据,并输出到控制台。在父进程中,关闭了管道的读端,通过 `write` 函数向管道中写入数据,并等待子进程执行完毕。在程序结束时,关闭了管道的写端。