Using select () with a pipe

I read / write to the pipe(pipe_fds) created by pipe(pipe_fds) . So basically with the following code, I read from this channel:

 fp = fdopen(pipe_fds[0], "r"); 

And when I ever get something, I print it:

 while (fgets(buf, 200, fp)) { printf("%s", buf); } 

I want when for some time nothing appears on the pipe until read , I want to know about it and do:

 printf("dummy"); 

Is it possible to do select () ? Any pointers on how to do this will be great.

+4
source share
2 answers

Let's say you wanted to wait 5 seconds, and then, if nothing was written into the pipe, you will print a “dummy”.

 fd_set set; struct timeval timeout; /* Initialize the file descriptor set. */ FD_ZERO(&set); FD_SET(pipe_fds[0], &set); /* Initialize the timeout data structure. */ timeout.tv_sec = 5; timeout.tv_usec = 0; /* In the interest of brevity, I'm using the constant FD_SETSIZE, but a more efficient implementation would use the highest fd + 1 instead. In your case since you only have a single fd, you can replace FD_SETSIZE with pipe_fds[0] + 1 thereby limiting the number of fds the system has to iterate over. */ int ret = select(FD_SETSIZE, &set, NULL, NULL, &timeout); // a return value of 0 means that the time expired // without any acitivity on the file descriptor if (ret == 0) { printf("dummy"); } else if (ret < 0) { // error occurred } else { // there was activity on the file descripor } 
+10
source

IIRC, select has a timeout that you then check with FD_ISSET to indicate whether it was returned / not or not.

0
source

All Articles