5.命名管道的数据通信

1.只读 open 要阻塞的代码:

#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<errno.h>
#include<fcntl.h>


int main()
{
       //int mkfifo(const char *pathname, mode_t mode);
      if( (mkfifo("./file",0600) == -1) && errno != EEXIST)
      {
           printf("mkfifo fialed\n");
           perror("why");
      }
      open("./file",O_RDONLY);
      printf("open success\n");
       return 0;
}

运行结果:

 

2.实现简单通信代码

(1)读取数据的代码:

#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<errno.h>
#include<fcntl.h>


int main()
{
       //int mkfifo(const char *pathname, mode_t mode);
      if( (mkfifo("./file",0600) == -1) && errno != EEXIST)
      {
           printf("mkfifo fialed\n");
           perror("why");
      }
      open("./file",O_RDONLY);    //O_RDONLY 是以读打开FIFO
      printf("open success\n");
       return 0;
}

(2)写入数据的代码: 

#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<errno.h>
#include<fcntl.h>


int main()
{

      open("./file",O_WRONLY);    //O_WRONLY是以写打开一个FIFO
      printf("write open success\n");
       return 0;
}

 

运行结果:

 

3.通信代码

(1)读取数据的代码:

        read.c 

#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<errno.h>
#include<fcntl.h>


int main()
{
       //int mkfifo(const char *pathname, mode_t mode);
      char buf[30] = {0};

      if( (mkfifo("./file",0600) == -1) && errno != EEXIST)
      {
           printf("mkfifo fialed\n");
           perror("why");
      }
      int fd = open("./file",O_RDONLY);

      printf("open success\n");

      int n_read = read(fd,buf,30);
      printf("read %d byte form fifo,context:%s\n",n_read,buf);

      close(fd);
       return 0;
}

编译:gcc read.c -o read 

(2)写入数据的代码: 

          write.c

#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>

int main()
{
      char* str = "message form fifo";

      int fd = open("./file",O_WRONLY);
      printf("write open success\n");

      write(fd,str,strlen(str));

      close(fd);
       return 0;
}

编译:gcc write.c -o write  

(3)运行代码实现通信流程:

         先运行:./read 

         再运行: ./write 

(4)运行结果:

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值