comparison utils.c @ 0:6ce4443e7545

Add the draft of an API to collect statistics on LXC
author Louis Opter <kalessin@kalessin.fr>
date Wed, 29 Dec 2010 23:28:14 +0100
parents
children 50215911acb3
comparison
equal deleted inserted replaced
-1:000000000000 0:6ce4443e7545
1 #include <sys/types.h>
2 #include <sys/mman.h>
3 #include <sys/stat.h>
4
5 #include <assert.h>
6 #include <err.h>
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <dirent.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13
14 #include "_lxcstats.h"
15
16 char *
17 _lxcst_join_path(char *dest, size_t size, const char *left, const char *right)
18 {
19 if (*right != '/') {
20 _lxcst_strlcpy(dest, left, size);
21 _lxcst_strlcat(dest, "/", size);
22 _lxcst_strlcat(dest, right, size);
23 } else {
24 _lxcst_strlcpy(dest, right, size);
25 }
26
27 return (dest);
28 }
29
30 int
31 _lxcst_isdir(const struct _lxcst_controller *hdl, const struct dirent *d)
32 {
33 struct stat sb;
34 char buf[PATH_MAX];
35
36 _lxcst_join_path(buf, sizeof(buf), hdl->cgroup_dir, d->d_name);
37
38 if (stat(buf, &sb) == -1) {
39 warn("can't stat file: %s", buf);
40 return (0);
41 }
42
43 return (sb.st_mode & S_IFDIR);
44 }
45
46 /*
47 * Files under cgroups are virtual and always have a size of zero so we have to
48 * do some reallocs.
49 */
50 ssize_t
51 _lxcst_read_file(const char *path, char **content)
52 {
53 char buf[1024];
54 int fd;
55 ssize_t ret;
56 ssize_t size;
57 char *p;
58 int sverrno;
59
60 assert(path);
61 assert(content);
62
63 *content = NULL;
64 size = 0;
65
66 fd = open(path, O_RDONLY);
67 if (fd != -1) {
68
69 while (1) {
70 ret = read(fd, buf, sizeof(buf));
71 if (ret == -1) {
72 if (errno == EINTR)
73 continue ;
74 break ;
75 }
76 if (ret == 0)
77 break ;
78
79 p = realloc(*content, size + ret);
80 if (!p)
81 break ;
82
83 *content = p;
84 memcpy(&content[0][size], buf, ret);
85 size += ret;
86 }
87
88 if (*content) {
89 close(fd);
90 return (size);
91 }
92
93 sverrno = errno;
94 close(fd);
95 errno = sverrno;
96 }
97
98 free(*content);
99 return (ret);
100 }