experiments

All kinds of coding experiments
Log | Files | Refs | Submodules

fifo_poll.c (1409B)


      1 #include <errno.h>
      2 #include <fcntl.h>
      3 #include <poll.h>
      4 #include <stdio.h>
      5 #include <string.h>
      6 #include <sys/stat.h>
      7 #include <stdbool.h>
      8 #include <unistd.h>
      9 
     10 #define MAX_BUF 1024
     11 
     12 // Example use of poll()
     13 // Reads from and writes to same fifo, using poll() to watch POLLIN and POLLOUT
     14 // events and act when the fd is ready
     15 
     16 char * myfifo = "./this.fifo";
     17 
     18 int main()
     19 {
     20 	int fd;
     21 	/* create the FIFO (named pipe) */
     22 	mkfifo(myfifo, 0666);
     23 	/* open in nonblock to avoid waiting */
     24 	fd = open(myfifo, O_RDWR);
     25 	if (fd == -1) {
     26 		printf("main: %d\n", errno);
     27 		return 1;
     28 	}
     29 
     30 	// Variables to write return values and read data to 
     31 	int len, ret;
     32 	char input[MAX_BUF], output[MAX_BUF];
     33 
     34 	// Define array of pfd(s). Only one file descriptor in this case
     35 	struct pollfd pfds[1]; 
     36 	pfds[0].fd = fd;
     37 	pfds[0].events = POLLIN | POLLOUT; // Watch poll in and out events
     38 	while (strcmp(input, "exit\n")) {
     39 		ret = poll(pfds, 1, 1); 	// 1 fd, 1 second timeout
     40 		if (ret == -1) {
     41 			perror("poll");
     42 			return 1;
     43 		}
     44 		if (!ret) {
     45 			continue;
     46 		}
     47 		if (pfds[0].revents & POLLIN) {
     48 			len = read(fd, output, MAX_BUF);
     49 			printf("Received: %d bytes\n", len);
     50 			output[len] = '\0'; // ignore garbage from previous read
     51 			printf("Received: %s", output);
     52 			continue;
     53 		}
     54 		if (pfds[0].revents & POLLOUT) {
     55 			printf("> ");
     56 			fgets(input, MAX_BUF, stdin);
     57 			write(fd, input, strlen(input));
     58 		}
     59 	}
     60 	close(fd);
     61 
     62 	return 0;
     63 }