2 * This sample code shows how to use Libevent to read from a named pipe.
3 * XXX This code could make better use of the Libevent interfaces.
5 * XXX This does not work on Windows; ignore everything inside the _WIN32 block.
7 * On UNIX, compile with:
8 * cc -I/usr/local/include -o event-read-fifo event-read-fifo.c \
9 * -L/usr/local/lib -levent
12 #include <event2/event-config.h>
14 #include <sys/types.h>
17 #include <sys/queue.h>
31 #include <event2/event.h>
34 fifo_read(evutil_socket_t fd, short event, void *arg)
38 struct event *ev = arg;
43 fprintf(stderr, "fifo_read called with fd: %d, event: %d, arg: %p\n",
46 len = ReadFile((HANDLE)fd, buf, sizeof(buf) - 1, &dwBytesRead, NULL);
48 /* Check for end of file. */
49 if (len && dwBytesRead == 0) {
50 fprintf(stderr, "End Of File");
55 buf[dwBytesRead] = '\0';
57 len = read(fd, buf, sizeof(buf) - 1);
63 fprintf(stderr, "Connection closed\n");
65 event_base_loopbreak(event_get_base(ev));
71 fprintf(stdout, "Read: %s\n", buf);
74 /* On Unix, cleanup event.fifo if SIGINT is received. */
77 signal_cb(evutil_socket_t fd, short event, void *arg)
79 struct event_base *base = arg;
80 event_base_loopbreak(base);
85 main(int argc, char **argv)
88 struct event_base* base;
92 socket = CreateFileA("test.txt", /* open File */
93 GENERIC_READ, /* open for reading */
95 NULL, /* no security */
96 OPEN_EXISTING, /* existing file only */
97 FILE_ATTRIBUTE_NORMAL, /* normal file */
98 NULL); /* no attr. template */
100 if (socket == INVALID_HANDLE_VALUE)
104 struct event *signal_int;
106 const char *fifo = "event.fifo";
109 if (lstat(fifo, &st) == 0) {
110 if ((st.st_mode & S_IFMT) == S_IFREG) {
118 if (mkfifo(fifo, 0600) == -1) {
123 socket = open(fifo, O_RDONLY | O_NONBLOCK, 0);
130 fprintf(stderr, "Write data to %s\n", fifo);
132 /* Initalize the event library */
133 base = event_base_new();
135 /* Initalize one event */
137 evfifo = event_new(base, (evutil_socket_t)socket, EV_READ|EV_PERSIST, fifo_read,
140 /* catch SIGINT so that event.fifo can be cleaned up */
141 signal_int = evsignal_new(base, SIGINT, signal_cb, base);
142 event_add(signal_int, NULL);
144 evfifo = event_new(base, socket, EV_READ|EV_PERSIST, fifo_read,
148 /* Add it to the active events, without a timeout */
149 event_add(evfifo, NULL);
151 event_base_dispatch(base);
152 event_base_free(base);
159 libevent_global_shutdown();