Linux进程通信-无名管道pipe

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

进程A向管道写内容,进程B读取管道内容,这种行为符合队列的操作进程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.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值