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 );
      }
}

你可能感兴趣的:(mkfifo函数创建有名管道)