Skip to content

Instantly share code, notes, and snippets.

@paulproteus
Created June 10, 2020 19:38
Show Gist options
  • Save paulproteus/13df690f99ffed22e2d1048ab3deb523 to your computer and use it in GitHub Desktop.
Save paulproteus/13df690f99ffed22e2d1048ab3deb523 to your computer and use it in GitHub Desktop.
Select on a file
#include <stdio.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/select.h>
int main(void) {
int read_fd = open("example.txt", O_NONBLOCK | O_RDONLY);
int read_fd_nfds = read_fd + 1;
fd_set set1;
struct timeval timeout;
// initialize fd set1
FD_ZERO(&set1);
FD_SET(read_fd, &set1);
int select_val = 0;
select_val = select(read_fd_nfds, &set1, NULL, NULL, NULL);
printf("Got %d\n", select_val);
printf("Our fd is set? %d\n", FD_ISSET(read_fd, &set1));
// Read nothing from the FD, to satisfy things (?)
read(read_fd, NULL, 0);
// Hoping this select will block forever; unfortunately, it
// immediately succeeds.
FD_ZERO(&set1);
FD_SET(read_fd, &set1);
select_val = select(read_fd_nfds, &set1, NULL, NULL, NULL);
printf("Second select: got %d\n", select_val);
printf("Our fd is set? %d\n", FD_ISSET(read_fd, &set1));
return 0;
}
@paulproteus
Copy link
Author

Actual output:

Got 1
Our fd is set? 8
Second select: got 1
Our fd is set? 8

Expected output:

./a.out  
Got 1
Our fd is set? 8
(block forever)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment