程序间通信:FIFO

参考自:

http://publib.boulder.ibm.com/infocenter/zos/v1r10/index.jsp?topic=/com.ibm.zos.r10.bpxbd00/rtmkf.htm

 

程序间通信可以使用命名管道FIFO,在硬盘中建立管道文件。具体实例如下:

 

/**
 *gcc -g -o fifo_w fifo_w.c `pkg-config gtk+-2.0 --cflags --libs gthread-2.0`
 *
 */

#define _POSIX_SOURCE
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

main() {
  char fn[]="/tmp/temp.fifo";
  char out[20]="FIFO's are fun!";
  int wfd;

  if (mkfifo(fn, S_IRWXU) != 0)
    perror("mkfifo() error");
  else {
      if ((wfd = open(fn, O_WRONLY)) < 0)
        perror("open() error for write end");
      else {
        if (write(wfd, out, strlen(out)+1) == -1)
          perror("write() error");
        close(wfd);
      }
  }
  unlink(fn);
}

 

/**
 *gcc -g -o fifo_r fifo_r.c `pkg-config gtk+-2.0 --cflags --libs gthread-2.0`
 *
 */
#define _POSIX_SOURCE
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

main() {
  char fn[]="/tmp/temp.fifo";
  char in[20];
  int rfd;

  if ((rfd = open(fn, O_RDONLY|O_NONBLOCK)) < 0)
    perror("open() error for read end");
  else {
      if (read(rfd, in, sizeof(in)) == -1)
        perror("read() error");
      else printf("read '%s' from the FIFO\n", in);
    }
  close(rfd);
}

 

运行结果:

terminal1:

[socol@localhost gtk]$ ./fifo_w

 

terminal2:
[socol@localhost gtk]$ ./fifo_r

read 'FIFO's are fun!' from the FIFO

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值