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