Mercurial > archived > louis > perso > liblxcstats
view utils.c @ 4:50215911acb3
Add a strsplit() function and stop to build probes into a separate library
author | Louis Opter <louis@dotcloud.com> |
---|---|
date | Sat, 01 Jan 2011 16:01:19 +0100 |
parents | 6ce4443e7545 |
children | 8339ab15527d |
line wrap: on
line source
#include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <assert.h> #include <ctype.h> #include <err.h> #include <errno.h> #include <fcntl.h> #include <dirent.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "_lxcstats.h" char * _lxcst_join_path(char *dest, size_t size, const char *left, const char *right) { if (*right != '/') { _lxcst_strlcpy(dest, left, size); _lxcst_strlcat(dest, "/", size); _lxcst_strlcat(dest, right, size); } else { _lxcst_strlcpy(dest, right, size); } return (dest); } int _lxcst_isdir(const struct _lxcst_controller *hdl, const struct dirent *d) { struct stat sb; char buf[PATH_MAX]; _lxcst_join_path(buf, sizeof(buf), hdl->cgroup_dir, d->d_name); if (stat(buf, &sb) == -1) { warn("can't stat file: %s", buf); return (0); } return (sb.st_mode & S_IFDIR); } /* * Files under cgroups are virtual and always have a size of zero so we have to * do some reallocs. */ ssize_t _lxcst_read_file(const char *path, char **content) { char buf[1024]; int fd; ssize_t ret; ssize_t size; char *p; int sverrno; assert(path); assert(content); *content = NULL; size = 0; fd = open(path, O_RDONLY); if (fd != -1) { while (1) { ret = read(fd, buf, sizeof(buf)); if (ret == -1) { if (errno == EINTR) continue ; break ; } if (ret == 0) break ; p = realloc(*content, size + ret); if (!p) break ; *content = p; memcpy(&content[0][size], buf, ret); size += ret; } if (*content) { close(fd); return (size); } sverrno = errno; close(fd); errno = sverrno; } free(*content); return (ret); } int _lxcst_strsplit(char *str, char **fields, size_t nfields) { char prev; int i; prev = ' '; i = 0; while (*str && nfields) { if (!isspace(*str)) { if (isspace(prev)) { /* new word */ fields[i] = str; ++i; --nfields; } prev = *str; } else { prev = *str; *str = '\0'; } str++; } return (i); }