9

I am trying to write a program where i need to monitor ends of unnamed pipe for certain events. Can I use unnamed pipes with poll function?

If yes, can you please show me the syntax for poll function with functional descriptors

dlmeetei
  • 9,905
  • 3
  • 31
  • 38
chaitu
  • 1,036
  • 5
  • 20
  • 39
  • 2
    poll() and other event reporting interfaces (select, epoll) work with almost all types of file descriptors, including unnamed pipes. You use it with unnamed pipes exactly the same way as you would with named pipes or network sockets. – Ambroz Bizjak Apr 04 '12 at 09:28
  • 2
    "In UNIX, everything's a file", so yes. – tbert Apr 04 '12 at 09:31
  • "functional descriptor" is a terminological mistake. You mean "file descriptor" – Basile Starynkevitch Apr 04 '12 at 10:23

2 Answers2

6

An example of poll

To use poll to check if readfd is readable or writefd is writable:

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");
}
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
2

You don't need a name to use the poll(2) interface; simply include the filedescriptor in the array of struct pollfd that you pass to the system call as you would any other socket.

sarnold
  • 102,305
  • 22
  • 181
  • 238