Check return value of close()
[eleutheria.git] / kqueue / kqtimer.c
blob12160b1762c4d0ff33f96f461796dc3bb46a417c
1 /*
2 * Compile with:
3 * gcc kqtimer.c -o kqtimer -Wall -W -Wextra -ansi -pedantic
5 * The following code will setup a timer that will trigger a
6 * kevent every 5 seconds. Once it does, the process will fork
7 * and the child will execute the date(1) command.
8 */
10 #include <sys/event.h>
11 #include <sys/time.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h> /* for strerror() */
15 #include <unistd.h>
17 /* Function prototypes */
18 void diep(const char *s);
20 int main(void)
22 struct kevent change; /* event we want to monitor */
23 struct kevent event; /* event that was triggered */
24 pid_t pid;
25 int kq, nev;
27 /* Create a new kernel event queue */
28 if ((kq = kqueue()) == -1)
29 diep("kqueue()");
31 /* Initalise kevent structure */
32 EV_SET(&change, 1, EVFILT_TIMER, EV_ADD | EV_ENABLE, 0, 5000, 0);
34 /* Loop forever */
35 for (;;) {
36 nev = kevent(kq, &change, 1, &event, 1, NULL);
38 if (nev < 0)
39 diep("kevent()");
41 else if (nev > 0) {
42 if (event.flags & EV_ERROR) { /* report any error */
43 fprintf(stderr, "EV_ERROR: %s\n", strerror(event.data));
44 exit(EXIT_FAILURE);
47 if ((pid = fork()) < 0) /* fork error */
48 diep("fork()");
50 else if (pid == 0) /* child */
51 if (execlp("date", "date", (char *)0) < 0)
52 diep("execlp()");
56 /* Close kqueue */
57 if (close(kq) == -1)
58 diep("close()");
60 return EXIT_SUCCESS;
63 void diep(const char *s)
65 perror(s);
66 exit(EXIT_FAILURE);