进程间通信(IPC)之 无名管道

一、管道

管道通常是指无名管道,是UNIX系统IPC最古老的形式

特点:

  1. 它是半双工(即数据只能在一个方向上流动),具有固定的读端和写端。

  1. 它只能用于具有亲缘关系的进程之间的通信(也是父子进程或者兄弟进程之间)。

  1. 它可以看成是一种特殊的文件,对于它的读写也可以使用普通的read、write等函数。但是它不是普通的文件,并不属于任何文件系统,并且只存在于内存中。

原型:

#include <unistd.h>
int pipe(int pipefd[2]);  // 返回值:成功返回0,失败返回-1

当一个管道建立时,就会创建两个文件描述符:fd[0]为读而打开,fd[1]为写而打开。

例子:(无名管道)

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
// int pipe(int pipefd[2]);
int main()
{
        int fd[2];
        int pid;
        char buf[128];
        if(pipe(fd) == -1){
                printf("create pipe failed\n");
        }
        pid = fork();
        if(pid < 0){
                printf("create child failed\n");
        }
        else if(pid > 0){
                sleep(3);
                printf("this is father\n");
                close(fd[0]);
                write(fd[1], "hello from father", strlen("hello from father"));
                wait();
        }else{
                printf("this is child\n");
                close(fd[1]);
                read(fd[0], buf, 128);
                printf("read from father: %s\n",buf);
                exit(0);
        }
        return 0;
}

无名管道有如下缺点:

  1. 不能使用open打开

  1. 只能父子进程间通信

  1. 半双工工作方式,读写端是分开的,fd[0]为读段,fd[1]写段

  1. 写入操作不具有原子性,只能用于一对一简单通信

  1. 不能用lseek来定位

注意:

管道有固定的读端和写端,管道为空,read()会阻塞,管道满时,write会阻塞。在操作管道是,要求读、写端都存在,写端关闭时,read直接返回,返回值为0。读端关闭时,write()会产生异常,收到SIGPIPE信号。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值