Last active
December 29, 2018 20:04
-
-
Save catvec/08d51d54e28a774d6896de99942d94e9 to your computer and use it in GitHub Desktop.
Named Fifo Select Bug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <errno.h> | |
#include <sys/select.h> | |
#include <stdlib.h> | |
#include <fcntl.h> | |
#include <stdio.h> | |
#include <stdbool.h> | |
#include <unistd.h> | |
#include <string.h> | |
int main() { | |
// Open export fifo | |
int fd = open("./foo-fifo", O_RDWR | O_CREAT); | |
if (fd < 0) { // Failed to open | |
perror("error opening fifo"); | |
} | |
// Read or write fifo until "quit" is in buffer | |
while (true) { | |
fd_set read_fds; | |
fd_set write_fds; | |
FD_ZERO(&read_fds); | |
FD_SET(fd, &read_fds); | |
FD_ZERO(&write_fds); | |
FD_SET(fd, &write_fds); | |
int num_fds = select(fd+1, &read_fds, &write_fds, NULL, NULL); | |
if (num_fds < 0) { // Failed to select | |
perror("failed to select fifo fd"); | |
} else if (num_fds == 0) { // Timeout | |
continue; | |
} | |
// If read | |
if (FD_ISSET(fd, &read_fds)) { | |
char buf[1000] = ""; | |
if (read(fd, buf, sizeof(buf)) < 0) { | |
perror("error reading fifo"); | |
} | |
printf("read: \"%s\"\n", buf); | |
if (strcmp(buf, "quit\n") == 0) { | |
break; | |
} | |
} | |
// If write | |
if (FD_ISSET(fd, &write_fds)) { | |
char *buf = "foo"; | |
if (write(fd, buf, sizeof(buf)) < 0) { | |
perror("error writing fifo"); | |
} | |
printf("write: \"%s\"\n", buf); | |
} | |
} | |
// Close fifo | |
if (close(fd) < 0) { // Failed to close | |
perror("failed to close export fifo"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment