diff options
Diffstat (limited to 'src/libsystem/proc.c')
-rw-r--r-- | src/libsystem/proc.c | 95 |
1 files changed, 95 insertions, 0 deletions
diff --git a/src/libsystem/proc.c b/src/libsystem/proc.c new file mode 100644 index 0000000..acac082 --- /dev/null +++ b/src/libsystem/proc.c @@ -0,0 +1,95 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/* + * libsystem + * + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <stdlib.h> +#include <string.h> +#include <errno.h> +#include <assert.h> + +#include "libsystem.h" + +/* In old kernel, this symbol maybe NOT */ +#ifndef TASK_COMM_LEN +#define TASK_COMM_LEN 16 +#endif + +ssize_t cmdline_get_str(char **buf, const char *op) { + _cleanup_free_ char *cmdline = NULL; + char *s, *w, *state; + size_t l, ll; + int r; + + assert(buf); + assert(op); + + r = read_one_line_from_path("/proc/cmdline", &cmdline); + if (r < 0) + return r; + + ll = strlen(op); + FOREACH_WORD(w, l, cmdline, state) + if (strneq(op, w, ll)) { + s = new0(char, l - ll + 1); + if (!s) + return -ENOMEM; + + strncpy(s, w + ll, l - ll + 1); + + *buf = s; + + return l - ll + 1; + } + + return -ENOENT; +} + +int pid_of(const char *pname) { + _cleanup_closedir_ DIR *dir = NULL; + struct dirent *de; + int r; + + dir = opendir("/proc"); + if (!dir) + return -errno; + + FOREACH_DIRENT(de, dir, return -errno) { + _cleanup_free_ char *path = NULL; + _cleanup_free_ char *comm = NULL; + + if (de->d_type != DT_DIR) + continue; + + if (!is_number(de->d_name, strlen(de->d_name))) + continue; + + r = asprintf(&path, "/proc/%s/comm", de->d_name); + if (r < 0) + return -ENOMEM; + + r = read_one_line_from_path(path, &comm); + if (r < 0) + continue; + + if (strneq(pname, comm, TASK_COMM_LEN-1)) + return atoi(de->d_name); + } + + return 0; +} |