]> git.proxmox.com Git - mirror_lxc.git/blob - src/liblxc/monitor.c
Initial revision
[mirror_lxc.git] / src / liblxc / monitor.c
1 /*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2008
5 *
6 * Authors:
7 * Daniel Lezcano <dlezcano at fr.ibm.com>
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 */
23 #include <stdio.h>
24 #include <errno.h>
25 #include <unistd.h>
26 #include <string.h>
27 #include <fcntl.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/param.h>
31 #include <sys/inotify.h>
32 #include <netinet/in.h>
33 #include <net/if.h>
34
35 #include <lxc.h>
36 #include <state.h>
37 #include <log.h>
38
39 int lxc_monitor(const char *name, int output_fd)
40 {
41 char path[MAXPATHLEN];
42 int err = -1, nfd, wfd, state;
43
44 nfd = inotify_init();
45 if (nfd < 0) {
46 lxc_log_syserror("failed to initialize inotify");
47 return -1;
48 }
49
50 snprintf(path, MAXPATHLEN, LXCPATH "/%s/state", name);
51
52 wfd = inotify_add_watch(nfd, path, IN_DELETE_SELF|IN_CLOSE_WRITE);
53 if (wfd < 0) {
54 lxc_log_syserror("failed to add a watch on %s", path);
55 goto out;
56 }
57
58 for(;;) {
59 struct inotify_event evt;
60
61 if (read(nfd, &evt, sizeof(evt)) < 0) {
62 lxc_log_syserror("failed to read inotify event");
63 goto out;
64 }
65
66 if (evt.mask & IN_CLOSE_WRITE) {
67
68 state = lxc_getstate(name);
69 if (state < 0) {
70 lxc_log_error("failed to get the state for %s",
71 name);
72 goto out;
73 }
74
75 if (write(output_fd, &state, sizeof(state)) < 0) {
76 lxc_log_syserror("failed to send state to %d",
77 output_fd);
78 goto out;
79 }
80 continue;
81 }
82
83 if (evt.mask & IN_DELETE_SELF) {
84 close(output_fd);
85 err = 0;
86 goto out;
87 }
88
89 lxc_log_error("unknown evt for inotity (%d)", evt.mask);
90 goto out;
91 }
92
93 out:
94 inotify_rm_watch(nfd, wfd);
95 close(nfd);
96 return err;
97 }