Introduce old redir program
[lcapit-junk-code.git] / snippets / C / select.c
blob0dbfed0fe7881f0c429d141fcff9a9e012c6d554
1 /*
2 * select() example, you can test by doing:
3 *
4 * $ mkfifo my-fifo
5 * $ cc -o select select.c
6 * $ ./select my-fifo
7 *
8 * And, in other terminal:
9 *
10 * $ echo 'Hello, world!' > my-fifo
12 * Luiz Fernando N. Capitulino
13 * <lcapitulino@gmail.com>
15 #include <stdio.h>
16 #include <unistd.h>
17 #include <stdlib.h>
18 #include <fcntl.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/select.h>
23 int main(int argc, char *argv[])
25 char c;
26 int err, fd;
27 fd_set rset;
28 ssize_t bytes;
30 if (argc != 2) {
31 printf("usage: select < fifo-path >");
32 exit(1);
35 fd = open(argv[1], O_RDONLY);
36 if (fd < 0) {
37 perror("open()");
38 exit(1);
42 * select() receives a set fo file-descriptors to
43 * monitor. The 'fd_set' data type should be used
44 * to define the set variable.
46 * Before calling select() you have to:
48 * 1. Initialize each set with FD_ZERO()
49 * 2. Add file-descriptors to the set
51 FD_ZERO(&rset);
52 FD_SET(fd, &rset);
55 * The first parameter is always confusing to
56 * most people...
58 * The rule is simple: it's the highest-numbered
59 * file descriptor in any of the sets, plus 1.
61 * In this example we only have one file-descriptor,
62 * so all we have to do is to add 1 to it. But if you
63 * have, say, 30 file-descriptors, you'll have to
64 * find the highest one and add 1 to it.
66 err = select(fd + 1, &rset, NULL, NULL, NULL);
67 if (err < 0) {
68 perror("select()");
69 exit(1);
72 if (FD_ISSET(fd, &rset)) {
73 for (;;) {
74 bytes = read(fd, &c, 1);
75 if (bytes == 0)
76 break;
77 if (bytes < 0) {
78 perror("read()");
79 exit(1);
81 if (bytes != 1) {
82 fprintf(stderr,
83 "Something strange has happend\n");
84 exit(1);
86 printf("%c", c);
88 } else {
89 fprintf(stderr, "select() returned but fd is not set\n");
90 exit(1);
93 return 0;