Linux系统编程之管道

  • 管道是进程间通信的手段之一,在这之前,普通文件是最基本的通信方式,而普通文件通信的问题在于,A进程对文件写进了内容,B进程无法感知这种变化,而管道正好解决了这种问题。

  • 管道的使用方法
    创建管道的进程fifoA:

    1. 创建管道
    2. 打开管道
    3. 写数据
    4. 关闭管道
    5. 删除管道

    接收数据的进程fifoB

    1. 打开管道
    2. 读取数据
    3. 关闭管道
      管道文件只能由其创建者删除,而接受者在关闭后重新打开,可以继续接收管道的数据。,举个栗子。。

fifoA.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>

int fd;
int i;

void handle(int s){
    if(s==SIGINT){
        close(fd);
        unlink("main.pipo");
        exit(-1);
    }


    //close fifo
    //delete fifo
}

int main(){


    //craete a fifo file
    mkfifo("main.fifo",0666);
    //open the fifo
    fd=open("main.fifo",O_RDWR);

    //write data
    while(1){
        write(fd,&i,4);
        sleep(1);
        ++i;
    }
    return 0;
}

fifoB.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>

int fd;
int i;
void handle(int s){

    if(s==SIGINT){
        close(fd);
        exit(-1);
    }
}


int main(){

    signal(SIGINT,handle);
    //open fifo file
    fd=open("main.fifo",O_RDONLY);
    i=0;
    while(1){
        read(fd,&i,4);
        printf("%d\n",i);
    }

    return 0;
}

其中关闭管道由一个信号处理事件完成。先打开A,然后打开B,中间可以保持A开启,而B多次关闭打开,查看运行结果,这里就不再截图了。

  1. 没有数据时,read阻塞,而且read后数据被删除
  2. 数据有序
  3. 打开的描述符号可以读写
  4. 管道文件关闭后,数据不持久
  5. 管道的数据存储在内核缓冲区中
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值