using select on a fifo

The right way to handle on-going input from file descriptors is to use select(). All readable events are flagged (one such event is “end of file”, which is indicated by a 0-sized read()). For example, if we’re reading from file descriptor fd:

  fd_set rfds;
  int rc;

  FD_ZERO(&rfds);
  FD_SET(fd, &rfds);

  tv.tv_sec = 1;
  tv.tv_usec = 0;

  rc = select(fd + 1, &rfds, NULL, NULL, &tv);
  if (rc > 0) {
    char buf[80];
    ssize_t got = read(fd, buf, sizeof(buf));
    if (got < 0) {
      perror("read");
      return 1;
    }
    else if (got == 0) {
      printf("EOFn");
      return 1;
    }
    else {
      printf("read bytes: %dn", got);
    }
  }

When dealing with sockets, the above loop is sane — EOF means the other end hung up and you’ll never get more data from the file descriptor. In the case of a FIFO, however, “0 length read” means there are no more FIFO writers — but more could attach later and continue feeding in data! The problem with this is that select misbehaves and marks the file descriptor as “EOF” forever. Only the initial select() call blocks until there is something to read — once it hits EOF, select will always immediately return, defeating the purpose of select().

One solution is to re-open the FIFO, but you might miss writers between your 0-length read() and the next open().

The seemingly correct solution is rather simple: the FIFO reader should open the FIFO as a writer also. In this case, select() never thinks all the writers have vanished, so there is never an EOF condition, and the reader never misses any writers. So, instead of O_RDONLY, use:

fd = open(FIFO_PATHNAME, O_RDWR | O_NONBLOCK);
[@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/24790158/viewspace-1041143/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/24790158/viewspace-1041143/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值