xref: /freebsd/contrib/libevent/sample/time-test.c (revision 069ac184)
1 /*
2  * XXX This sample code was once meant to show how to use the basic Libevent
3  * interfaces, but it never worked on non-Unix platforms, and some of the
4  * interfaces have changed since it was first written.  It should probably
5  * be removed or replaced with something better.
6  *
7  * Compile with:
8  * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
9  */
10 
11 #include <sys/types.h>
12 
13 #include <event2/event-config.h>
14 
15 #include <sys/stat.h>
16 #ifndef _WIN32
17 #include <sys/queue.h>
18 #include <unistd.h>
19 #endif
20 #include <time.h>
21 #ifdef EVENT__HAVE_SYS_TIME_H
22 #include <sys/time.h>
23 #endif
24 #include <fcntl.h>
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <errno.h>
29 
30 #include <event2/event.h>
31 #include <event2/event_struct.h>
32 #include <event2/util.h>
33 
34 #ifdef _WIN32
35 #include <winsock2.h>
36 #endif
37 
38 struct timeval lasttime;
39 
40 int event_is_persistent;
41 
42 static void
43 timeout_cb(evutil_socket_t fd, short event, void *arg)
44 {
45 	struct timeval newtime, difference;
46 	struct event *timeout = arg;
47 	double elapsed;
48 
49 	evutil_gettimeofday(&newtime, NULL);
50 	evutil_timersub(&newtime, &lasttime, &difference);
51 	elapsed = difference.tv_sec +
52 	    (difference.tv_usec / 1.0e6);
53 
54 	printf("timeout_cb called at %d: %.3f seconds elapsed.\n",
55 	    (int)newtime.tv_sec, elapsed);
56 	lasttime = newtime;
57 
58 	if (! event_is_persistent) {
59 		struct timeval tv;
60 		evutil_timerclear(&tv);
61 		tv.tv_sec = 2;
62 		event_add(timeout, &tv);
63 	}
64 }
65 
66 int
67 main(int argc, char **argv)
68 {
69 	struct event timeout;
70 	struct timeval tv;
71 	struct event_base *base;
72 	int flags;
73 
74 #ifdef _WIN32
75 	WORD wVersionRequested;
76 	WSADATA wsaData;
77 
78 	wVersionRequested = MAKEWORD(2, 2);
79 
80 	(void)WSAStartup(wVersionRequested, &wsaData);
81 #endif
82 
83 	if (argc == 2 && !strcmp(argv[1], "-p")) {
84 		event_is_persistent = 1;
85 		flags = EV_PERSIST;
86 	} else {
87 		event_is_persistent = 0;
88 		flags = 0;
89 	}
90 
91 	/* Initialize the event library */
92 	base = event_base_new();
93 
94 	/* Initialize one event */
95 	event_assign(&timeout, base, -1, flags, timeout_cb, (void*) &timeout);
96 
97 	evutil_timerclear(&tv);
98 	tv.tv_sec = 2;
99 	event_add(&timeout, &tv);
100 
101 	evutil_gettimeofday(&lasttime, NULL);
102 
103 	setbuf(stdout, NULL);
104 	setbuf(stderr, NULL);
105 
106 	event_base_dispatch(base);
107 
108 	return (0);
109 }
110 
111