Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / third_party / libevent / sample / event-test.c
blob2c6cb93864c7efa985d5e62fd4cbdb05e0e47947
1 /*
2 * Compile with:
3 * cc -I/usr/local/include -o event-test event-test.c -L/usr/local/lib -levent
4 */
6 #ifdef HAVE_CONFIG_H
7 #include "config.h"
8 #endif
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #ifndef WIN32
13 #include <sys/queue.h>
14 #include <unistd.h>
15 #include <sys/time.h>
16 #else
17 #include <windows.h>
18 #endif
19 #include <fcntl.h>
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <errno.h>
25 #include <event.h>
27 static void
28 fifo_read(int fd, short event, void *arg)
30 char buf[255];
31 int len;
32 struct event *ev = arg;
33 #ifdef WIN32
34 DWORD dwBytesRead;
35 #endif
37 /* Reschedule this event */
38 event_add(ev, NULL);
40 fprintf(stderr, "fifo_read called with fd: %d, event: %d, arg: %p\n",
41 fd, event, arg);
42 #ifdef WIN32
43 len = ReadFile((HANDLE)fd, buf, sizeof(buf) - 1, &dwBytesRead, NULL);
45 // Check for end of file.
46 if(len && dwBytesRead == 0) {
47 fprintf(stderr, "End Of File");
48 event_del(ev);
49 return;
52 buf[dwBytesRead] = '\0';
53 #else
54 len = read(fd, buf, sizeof(buf) - 1);
56 if (len == -1) {
57 perror("read");
58 return;
59 } else if (len == 0) {
60 fprintf(stderr, "Connection closed\n");
61 return;
64 buf[len] = '\0';
65 #endif
66 fprintf(stdout, "Read: %s\n", buf);
69 int
70 main (int argc, char **argv)
72 struct event evfifo;
73 #ifdef WIN32
74 HANDLE socket;
75 // Open a file.
76 socket = CreateFile("test.txt", // open File
77 GENERIC_READ, // open for reading
78 0, // do not share
79 NULL, // no security
80 OPEN_EXISTING, // existing file only
81 FILE_ATTRIBUTE_NORMAL, // normal file
82 NULL); // no attr. template
84 if(socket == INVALID_HANDLE_VALUE)
85 return 1;
87 #else
88 struct stat st;
89 const char *fifo = "event.fifo";
90 int socket;
92 if (lstat (fifo, &st) == 0) {
93 if ((st.st_mode & S_IFMT) == S_IFREG) {
94 errno = EEXIST;
95 perror("lstat");
96 exit (1);
100 unlink (fifo);
101 if (mkfifo (fifo, 0600) == -1) {
102 perror("mkfifo");
103 exit (1);
106 /* Linux pipes are broken, we need O_RDWR instead of O_RDONLY */
107 #ifdef __linux
108 socket = open (fifo, O_RDWR | O_NONBLOCK, 0);
109 #else
110 socket = open (fifo, O_RDONLY | O_NONBLOCK, 0);
111 #endif
113 if (socket == -1) {
114 perror("open");
115 exit (1);
118 fprintf(stderr, "Write data to %s\n", fifo);
119 #endif
120 /* Initalize the event library */
121 event_init();
123 /* Initalize one event */
124 #ifdef WIN32
125 event_set(&evfifo, (int)socket, EV_READ, fifo_read, &evfifo);
126 #else
127 event_set(&evfifo, socket, EV_READ, fifo_read, &evfifo);
128 #endif
130 /* Add it to the active events, without a timeout */
131 event_add(&evfifo, NULL);
133 event_dispatch();
134 #ifdef WIN32
135 CloseHandle(socket);
136 #endif
137 return (0);