Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

c - can we use poll function with unnamed pipes?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...