]> git.saurik.com Git - apple/launchd.git/blob - launchd/doc/sampled.c
launchd-106.3.tar.gz
[apple/launchd.git] / launchd / doc / sampled.c
1 #include <sys/types.h>
2 #include <sys/event.h>
3 #include <sys/socket.h>
4 #include <sys/time.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdbool.h>
8 #include <unistd.h>
9 #include <string.h>
10 #include <errno.h>
11 #include <fcntl.h>
12 #include <syslog.h>
13 #include <libgen.h>
14
15 #include "launch.h"
16
17 int main(void)
18 {
19 struct timespec timeout = { 60, 0 };
20 struct sockaddr_storage ss;
21 socklen_t slen = sizeof(ss);
22 struct kevent kev;
23 launch_data_t tmp, resp, msg = launch_data_new_string(LAUNCH_KEY_CHECKIN);
24 size_t i;
25 int kq;
26
27 openlog(getprogname(), LOG_PERROR|LOG_PID|LOG_CONS, LOG_DAEMON);
28
29 if (-1 == (kq = kqueue())) {
30 syslog(LOG_ERR, "kqueue(): %m");
31 exit(EXIT_FAILURE);
32 }
33
34 if ((resp = launch_msg(msg)) == NULL) {
35 syslog(LOG_ERR, "launch_msg(\"" LAUNCH_KEY_CHECKIN "\") IPC failure: %m");
36 exit(EXIT_FAILURE);
37 }
38
39 if (LAUNCH_DATA_ERRNO == launch_data_get_type(resp)) {
40 errno = launch_data_get_errno(resp);
41 syslog(LOG_ERR, "Check-in failed: %m");
42 exit(EXIT_FAILURE);
43 }
44
45 tmp = launch_data_dict_lookup(resp, LAUNCH_JOBKEY_TIMEOUT);
46 if (tmp)
47 timeout.tv_sec = launch_data_get_integer(tmp);
48
49 tmp = launch_data_dict_lookup(resp, LAUNCH_JOBKEY_SOCKETS);
50 if (NULL == tmp) {
51 syslog(LOG_ERR, "No sockets found to answer requests on!");
52 exit(EXIT_FAILURE);
53 }
54
55 if (launch_data_dict_get_count(tmp) > 1) {
56 syslog(LOG_WARNING, "Some sockets will be ignored!");
57 }
58
59 tmp = launch_data_dict_lookup(tmp, "SampleListeners");
60 if (NULL == tmp) {
61 syslog(LOG_ERR, "No known sockets found to answer requests on!");
62 exit(EXIT_FAILURE);
63 }
64
65 for (i = 0; i < launch_data_array_get_count(tmp); i++) {
66 launch_data_t tmpi = launch_data_array_get_index(tmp, i);
67
68 EV_SET(&kev, launch_data_get_fd(tmpi), EVFILT_READ, EV_ADD, 0, 0, NULL);
69 if (kevent(kq, &kev, 1, NULL, 0, NULL) == -1) {
70 syslog(LOG_DEBUG, "kevent(): %m");
71 exit(EXIT_FAILURE);
72 }
73 }
74
75 launch_data_free(msg);
76 launch_data_free(resp);
77
78 for (;;) {
79 FILE *c;
80 int r;
81
82 if ((r = kevent(kq, NULL, 0, &kev, 1, &timeout)) == -1) {
83 syslog(LOG_ERR, "kevent(): %m");
84 exit(EXIT_FAILURE);
85 } else if (r == 0) {
86 exit(EXIT_SUCCESS);
87 }
88
89 if ((r = accept(kev.ident, (struct sockaddr *)&ss, &slen)) == -1) {
90 syslog(LOG_ERR, "accept(): %m");
91 continue; /* this isn't fatal */
92 }
93
94 c = fdopen(r, "r+");
95
96 if (c) {
97 fprintf(c, "hello world!\n");
98 fclose(c);
99 } else {
100 close(r);
101 }
102 }
103 }