赞
踩
int pipe(int fd[2])
#include <unistd.h>
#include <unistd.h> #include <iostream> #include <string.h> using namespace std; int main() { int pid = fork(); int fd[2]={0}; if (pipe(fd) < 0){ cout << "pipe error" << endl; return -1; } char buf[128] {0}; cout << "pid:" << pid << ";" << fd[0] << ";" << fd[1] << endl; if (pid > 0) { // 父进程 close(fd[1]); // 关闭写端 cout << "等待子进程输入" << endl; read(fd[0], buf, 128); cout << "子进程输入: " << buf << endl; close(fd[0]); } else if (pid == 0) { // 子进程 close(fd[0]); // 关闭读端 sleep(1); sprintf(buf, "hello"); cout << "子进程输入" << buf << endl; write(fd[1], buf, sizeof(buf)); // close(fd[1]); } else { cout << "fork error" << endl; return -1; } if (pid > 0) { // 等待子进程结束 int status; waitpid(pid, &status, 0); } return 0; }
cout << "pid:" << pid << ";" << fd[0] << ";" << fd[1] << endl;
。不关事子进程还是父进程对于fd的输出是一致的。产生这种写过的原因是pipe函数在父子进程之间创建的机制决定的Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。