当前位置:   article > 正文

c语言-管道-有名管道_c语言有名管道

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;
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

向管道写数据

#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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

向管道读取数据

#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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/837651
推荐阅读
相关标签
  

闽ICP备14008679号