进程间通信_02匿名管道

来源:互联网 发布:ag外设淘宝店 编辑:程序博客网 时间:2024/05/13 01:16
相关介绍
                    
分配一块独立于进程的内存,对内存的操作方式和对文件的操作方式类似。有如下特点:
1  只能用于父子进程之间。
2  管道的大小是有限制(一个页面的大小,4K字节)。
3  数据是单向流动的。
4  传送的是无格式字节流,需要双方事先确定好长度 格式等。



操作函数
1 创建一个管道
#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;}


1 0
原创粉丝点击