管道相关介绍

一、无名管道

父子之间进行单向通信

 假设先父进程先运行,子进程先sleep(6)秒,结果就是read()函数发生了阻塞,因为没有数据给他读

  1 #include <string.h>
  2 #include<stdio.h>
  3 #include<unistd.h>
  4 #include <stdlib.h>
  5 
  6 //       int pipe(int pipefd[2]);
  7 
  8 int main()
  9 {
 10         int pipefd[2];
 11         if(pipe(pipefd) == -1){
 12                 perror("why");
 13         }
 14 
 15         pid_t pid;
 16         pid = fork();
 17         if(pid == 0){
 18                 printf("child\n");
 19                 sleep(6);
 20                 close(pipefd[0]);
 21                 write(pipefd[1],"I wanna go home",16);
 22         }else if(pid > 0){
 23                 printf("father\n");
 24                 char readBuf[32]={0};
 25                 close(pipefd[1]);
 26                 read(pipefd[0],readBuf,16);
 27                 printf("readBuf context:%s\n",readBuf);
 28         }else{
 29                 perror("why");
 30         }
 31 
 32         return 0;
 33 }

二、有名管道或命名管道

FIFO创建:

  1 #include<stdio.h>
  2 #include <sys/types.h>
  3 #include <sys/stat.h>
  4 #include <errno.h>
  5 //       int mkfifo(const char *pathname, mode_t mode);
  6 
  7 int main()
  8 {
  9         if(mkfifo("./file",0600) == -1 && errno!=EEXIST){
 10                 perror("why");
 11         }
 12 
 13         return 0;
 14 }
~                                                                                         
~      

 发数据

  1 #include<stdio.h>
  2 #include <sys/types.h>
  3 #include <sys/stat.h>
  4 #include <errno.h>
  5 #include <unistd.h>
  6 #include <fcntl.h>
  7 
  8 //       int mkfifo(const char *pathname, mode_t mode);
  9 
 10 int main()
 11 {
 12         int fd = open("./file",O_WRONLY);
 13         write(fd,"hello,world",12);
 14         printf("write success\n");
 15 
 16         close(fd);
 17         return 0;
 18 }

 读数据

  1 #include<stdio.h>
  2 #include <sys/types.h>
  3 #include <sys/stat.h>
  4 #include <unistd.h>
  5 #include <fcntl.h>
  6 #include <errno.h>
  7 //       int mkfifo(const char *pathname, mode_t mode);
  8 
  9 int main()
 10 {
 11         if(mkfifo("./file",0600) == -1 && errno!=EEXIST){
 12                 perror("why");
 13         }
 14 
 15         int fd = open("./file",O_RDONLY);
 16         char readBuf[32] ={0};
 17         int n_read = read(fd,readBuf,32);
 18         printf("read %d byte to readBuf context:%s\n",n_read,readBuf);
 19 
 20         close(fd);
 21         return 0;
 22 }

=========================================================================

也可以一端一直写,另一端一直读,只要加循环就可以再加sleep(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值