我们可以使用带有未命名管道的poll函数吗?

时间:2012-04-04 09:24:24

标签: c linux pipe

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

如果是,请告诉我使用功能描述符的轮询功能的语法

2 个答案:

答案 0 :(得分:4)

民意调查的一个例子

使用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");
}

答案 1 :(得分:2)

您不需要名称来使用poll(2)界面;只需将filedescriptor包含在您传递给系统调用的struct pollfd数组中,就像任何其他套接字一样。

相关问题