mkfifo函数创建有名管道

pipe创建的管道只能在具有共同祖先的进程间通信,而mkfifo能在不相关的进程间交换数据。通俗举例来说,一个在一个c文件中通信,一个可在多个c文件中通信。
命名管道打开的规则:
为读打开FIFO:
O_NONBLOCK disable:阻塞直到有相应进程为写而打开FIFO
O_NONBLOCK enable:立刻返回成功
为写打开FIFO:
O_NONBLOCK disable:阻塞直到有相应进程为读而打开FIFO
O_NONBLOCK enable:立刻返回失败,错误码为ENXIO
打开文件描述符默认为阻塞。


管道创建与写管道程序:
#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
#include<fcntl.h>
#define SIZE 20

int main( int argc, char **argv )
{
      int fd;

      if( (mkfifo(argv[1], 0666)==-1) && (errno!=EEXIST) )//加后一半可令创建管道后的再次读取不输出错误提示!
      {
              perror( "create fifo error!" );
              exit( -1 );
      }
      if( (fd=open(argv[1], O_WRONLY)) == -1 )
      {
              perror( "open file error!" );
              exit( -1 );
      }
      write( fd, argv[2], SIZE );
      close( fd );
      puts( "write success!" );

      exit( 1 );
}


管道接收程序:
#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
#include<fcntl.h>
#include<stdlib.h>
#define SIZE 20

int main( int argc, char **argv )
{
      int fd;
      char buffer[SIZE];

      if( (fd=open(argv[1], O_RDONLY | O_NONBLOCK)) == -1 )
      {
              perror( "open file error!" );
              exit( -1 );
      }
      while( 1 )
      {
              memset( buffer, 0, SIZE );
              if( read(fd, buffer, SIZE) == -1 )
              {
                      perror( "please input something!" );
              }
              else
              {
                      printf( "receieve %s!", buffer );
              }
              sleep( 1 );
      }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值