程序:进程间通信——有名管道实例

来源:互联网 发布:叶子老师沪江辞职知乎 编辑:程序博客网 时间:2024/05/01 06:44

有名管道(命名管道)
命名管道无名管道基本相同,但也有不同点:无名管道只能由父子进程使用;但是通过命名管道,不相关的进程也能交换数据
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char * pathname, mode_t mode)
pathname:FIFO文件名
mode:属性(见文件操作章节)
    一旦创建了一个FIFO,就可用open打开它,一般的文件访问函数(close、read、write等)都可用于FIFO
以下程序分为两个部分,读文件和写文件。编译好后,在两个终端下执行,先执行写文件,再执行读文件
写文件 fifo_write.c#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include<sys/stat.h>
#define FIFO_SERVER "/tmp/fifoserver"
int main()
{
    int ret;          //创建管道文件函数的返回值,负数则创建失败
  int r_write;   //实际写进的个数
  int fd;           //管道文件描述符
    char w_buf[1024] ;   //写缓冲区
  int real_w;
  ret = mkfifo(FIFO_SERVER,O_CREAT|O_EXCL);  //  创建管道文件,文件名含路径
  if (ret < 0 && errno != EEXIST)   //如果ret小于零,并且不是因为文件已经存在发生的错误,则退出程序
  {
     printf("create fifo fail!");
    exit(-1);
  }
   
  fd = open(FIFO_SERVER,O_WRONLY);  //以只写方式打开管道文件
  
  if (fd< 0)
   {
        printf("open fail!");
  }
  while(1)               //循环在管道中写入
  {
      scanf("%s",w_buf);
      real_w = write(fd,w_buf,strlen(w_buf));
      if (real_w < 0)
      {
          printf("write fail!");
        exit(-1);
      }
      printf("%d %s",real_w,w_buf);
//    sleep(1);
  }
  unlink(FIFO_SERVER);         //与管道文件断开联系
    return 0;
}

写文件 fifo_read.c
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include<sys/stat.h>
#define FIFO_SERVER "/tmp/fifoserver"
int main()
{
    int ret;
  int r_read;
  int fd;
    char r_buf[1024];
  int real_r;
   
  fd = open(FIFO_SERVER,O_RDONLY);
  if (fd< 0)
  {
        printf("open fail!");
  }
  else
  {
      printf("open success");
  }
  while(1)
  {  
      printf("dsad");
      real_r = read(fd,r_buf,100);
      if (real_r < 0)
      {
          printf("read fail!");
        exit(-1);
      }
    sleep(1);
      printf("%d %s",real_r,r_buf);
  }
  unlink(FIFO_SERVER);
    return 0;
}
注意:若编译成功,运行时无法读出,在pintf()函数中添加'\n'
0 0
原创粉丝点击