命名管道的创建与使用

来源:互联网 发布:knockout.js easyui 编辑:程序博客网 时间:2024/06/05 02:02
 

实例1

  在一个程序中实现命名管道的创建与使用
  #include<sys/types.h>
  #include<sys/stat.h>
  #include<unistd.h>
  #include<fcntl.h>
  int main(void)
  {
  char buf[80];
  int fd;
  unlink( "zieckey_fifo" );
  mkfifo( "zieckey_fifo", 0777 );
  if ( fork() > 0 )
  {
  char s[] = "Hello!\n";
  fd = open( "zieckey_fifo", O_WRONLY );
  write( fd, s, sizeof(s) );
  //close( fd );
  }
  else
  {
  fd = open( "zieckey_fifo", O_RDONLY );
  read( fd, buf, sizeof(buf) );
  printf("The message from the pipe is:%s\n", buf );
  //close( fd );
  }
  return 0;
  }
  执行

  hello!

 

 

 

 

  此示例代码意在体现出命名管道与普通管道的区别,命名管道是以一个普通文件的形式出现的,包括三个文件,创建命名管道、写管道、读管道

  1. 创建命名管道
  #include<sys/types.h>
  #include<sys/stat.h>
  #include<unistd.h>
  #include<fcntl.h>
  int main(void)
  {
  char buf[80];
  int fd;
  unlink( "zieckey_fifo" );
  mkfifo( "zieckey_fifo", 0777 );

  }   

2. 写命名管道代码

  #include<sys/types.h>
  #include<sys/stat.h>
  #include<unistd.h>
  #include<fcntl.h>
  int main(void){
  int fd;
  char s[] = "Hello!\n";
  fd = open( "zieckey_fifo", O_WRONLY );
  while(1) {
  write( fd, s, sizeof(s) );
  sleep(1);
  }

 

3. 读命名管道代码

  #include<sys/types.h>

  #include<sys/stat.h>

  #include<unistd.h>

  #include<fcntl.h>

  int main(void){

  int fd;

  char buf[80];

  fd = open( "zieckey_fifo", O_RDONLY );

  while(1) {

  read( fd, buf, sizeof(buf) );

  printf("%s\n", buf);

  sleep(1);

  }

  return 0;

  }

  return 0;
  }