#include <unistd.h> int pipe( int fildes[2] ); //出参,用于管道读写端的文件描述符; 返回值:0(成功)/-1(失败,错误信息在errno中)
2 读管道
#include <unistd.h> ssize_t read( int fildes, //入参,读端的文件描述符,fildes[0] void* buf, //buf:出参,从管道读取的数据 size_t nbyte ); //nbyte:入参,从管道读取的数据的额长度 返回值:>= 0 从管道中读取的数据的长度 = -1 出错,错误信息在errno中
3 写管道
#include <unistd.h> ssize_t write( int fildes, //入参,写端的文件描述符,fildes[1] void* buf, //buf:入参,需要写入管道的数据 size_t nbyte ); //nbyte:入参,需要写入管带的数据的额长度 返回值:>= 0 写入管道的数据的长度 = -1 出错,错误信息在errno中
/************************************************************************* > File Name: testpipe.c > Author: qiaozp > Mail: qiaozongpeng@163.com > Created Time: 2014-9-15 11:03:08 > Step: 1 调用pipe函数在内核中创建一块存储区, 存储区有一个读端(fildes[0]) 和 写端(fildes[1]) 2 调用fork函数创建子进程 3 子进程负责写,关闭读端,写数据 4 父进程负责读,关闭写端,读数据 ************************************************************************/ #include <errno.h> #include <iostream> #include <unistd.h> using namespace std; int main() { char buff[100] = {0}; int pipeFd[2]; //create pipe if (pipe(pipeFd) == -1) { cout << "pipe error." << endl; return -1; } int desPid = fork(); if (desPid == 0) { cout << "son process for writing..." << endl; memset(buff, 0, sizeof(buff)); strcat(buff, "hello"); //close read, and write. close(pipeFd[0]); if (write(pipeFd[1], buff, sizeof(buff)) == -1) { cout << "son process failed to write pipe, errno is [" << errno << "]." << endl; } cout << "write data is : " << buff << endl; return 0; } else if (desPid > 0) { cout << "parent process for reading..." << endl; memset(buff, 0, sizeof(buff)); //close write and read. close(pipeFd[1]); if (read(pipeFd[0], buff, sizeof(buff)) == -1) { cout << "parent process failed to read pipe, errno is [" << errno << "]." << endl; } cout << "read data is : " << buff << endl; return 0; } else { cout << "failed to create child process, please check. errno is [" << errno << "]." << endl; return -1; } return 0; }
原文地址:http://blog.csdn.net/juncily/article/details/39290197