c语言-管道-有名管道

有名管道

特点:

  • 在磁盘上有这么一个文件, 当ls -l查看该文件时, 他的类型为p
  • 是一个伪文件,占用磁盘大小永远为0.数据存储在内核里.有一个对应的缓冲区.

fifo文件可以用io函数进行操作

  • open/close read/write 但不能用lseek

进程间通信:

  • 两个不相干的进程可以通信

使用场景:

  • 没有血缘关系的进程间通信

创建方式:

  • 命令方式创建: mkfifo 管道名
  • 函数方式创建: mkfifo函数

创建管道

 #include <stdio.h>
 #include <sys/types.h>
 #include <sys/stat.h>
  int main(int argc, char *argv[]) {
      int m = mkfifo(argv[1],0664);
      if(m == -1) {
      perror("mkfifo");
      return -1;
      }
      return 0;
  }

向管道写数据

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>    
#include <string.h>
int main(int argc, char *argv[]) {
    char *msg = "this is a test!\n";
    int fd =open(argv[1], O_WRONLY);
    if(fd == -1) {
    perror("open fifo faild");
    return -1;
    }
    write(fd, msg, strlen(msg));
    close(fd);
    return 0;
}

向管道读取数据

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>    
#include <string.h>
int main(int argc, char *argv[]) {
    char buf[128];
    int fd =open(argv[1], O_RDONLY);
    if(fd == -1) {
    perror("open fifo faild");
    return -1;
    }
    int r = read(fd, buf, 128);
    write(1, buf, r);
    close(fd);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北京时光

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值