天天看点

Linux进程通信-无名管道pipe

两个进程的通信使用无名管道pipe实现。pipe实际是创建队列实现先进先出,具体过程如下示意图:

Linux进程通信-无名管道pipe

进程A向管道写内容,进程B读取管道内容,这种行为符合队列的操作。

pipe函数

#include <unistd.h>

int pipe(int pipefd[2]);

pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe.

pipe的返回值为整形,创建管道成功返回1失败则返回-1。

//创建管道并进行读和写

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
    int fd[2];
    int ret;
    char writebuf[]="hello linux";
    char readbuf[128]={0};
    ret=pipe(fd);
    if(ret<0)
    {
        printf("creat pipe failur.\n");
        return -1;
    }
    printf("creat pipe sucess:fd(0)=%d,fd(1)=%d\n",fd[0],fd[1]);

    write(fd[1],writebuf,sizeof(writebuf));
    read(fd[0],readbuf,128);
    printf("readbuf=%s\n",readbuf);
    close(fd[0]);
    close(fd[1]);

    return 0;
}

           

创建成功fd[0]=3,fd[1]=4.

需要注意的是:当管道的内容为空时会发送读阻塞,当写的内容超过管道缓存的大小时会发生写阻塞。所以在进行管道的读写时需要注意管道的缓存大小。

继续阅读