【问题标题】:can we use poll function with unnamed pipes?我们可以对未命名的管道使用 poll 函数吗?
【发布时间】:2012-04-04 09:24:24
【问题描述】:

我正在尝试编写一个程序,在该程序中我需要监视未命名管道末端的某些事件。我可以使用带有轮询功能的未命名管道吗?

如果是,请给我看一下带有函数描述符的 poll 函数的语法

【问题讨论】:

  • poll() 和其他事件报告接口(select、epoll)适用于几乎所有类型的文件描述符,包括未命名的管道。将它用于未命名管道的方式与使用命名管道或网络套接字的方式完全相同。
  • “在 UNIX 中,一切都是文件”,是的。
  • “功能描述符”是一个术语错误。你的意思是“文件描述符”

标签: c linux pipe


【解决方案1】:

民意调查示例

使用poll 来检查readfd 是否可读或writefd 是否可写:

int readfd;
int writefd;

// initialize readfd & writefd, ...
// e.g. with: open(2), socket(2), pipe(2), dup(2) syscalls

struct pollfd fdtab[2];

memset (fdtab, 0, sizeof(fdtab)); // not necessary, but I am paranoid

// first slot for readfd polled for input
fdtab[0].fd = readfd;
fdtab[0].events = POLLIN;
fdtab[0].revents = 0;

// second slot with writefd polled for output
fdtab[1].fd = writefd;
fdtab[1].events = POLLOUT;
fdtab[1].revents = 0;

// do the poll(2) syscall with a 100 millisecond timeout
int retpoll = poll(fdtab, 2, 100);

if (retpoll > 0) {
   if (fdtab[0].revents & POLLIN) {
      /* read from readfd, 
         since you can read from it without being blocked */
   }
   if (fdtab[1].revents & POLLOUT) {
      /* write to writefd,
         since you can write to it without being blocked */
   }
}
else if (retpoll == 0) {
   /* the poll has timed out, nothing can be read or written */
}
else {
   /* the poll failed */
   perror("poll failed");
}

【讨论】:

    【解决方案2】:

    您不需要名称即可使用poll(2) 接口;只需将文件描述符包含在struct pollfd 的数组中,您可以像传递任何其他套接字一样将其传递给系统调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多