2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <sys/types.h>
25 #include "simple_util.h"
27 #define BINSH_NAME "/bin/sh"
30 #define PROC_STAT_GID_POS 5
33 static inline int __read_proc(const char *path, char *buf, int size);
34 static inline int __find_pid_by_cmdline(const char *dname,
35 const char *cmdline, void *priv);
36 static inline int __get_pgid_from_stat(int pid);
39 static inline int __read_proc(const char *path, char *buf, int size)
44 if (buf == NULL || path == NULL)
47 fd = open(path, O_RDONLY);
51 ret = read(fd, buf, size - 1);
63 static inline int __find_pid_by_cmdline(const char *dname,
64 const char *cmdline, void *priv)
69 apppath = (char *)priv;
70 if (strncmp(cmdline, apppath, MAX_LOCAL_BUFSZ-1) == 0) {
72 if (pid != getpgid(pid))
79 int __proc_iter_cmdline(
80 int (*iterfunc)(const char *dname, const char *cmdline, void *priv),
84 struct dirent *dentry;
87 char buf[MAX_LOCAL_BUFSZ];
89 dp = opendir("/proc");
95 iterfunc = __find_pid_by_cmdline;
97 while ((dentry = readdir(dp)) != NULL) {
98 if (!isdigit(dentry->d_name[0]))
101 snprintf(buf, sizeof(buf), "/proc/%s/cmdline", dentry->d_name);
102 ret = __read_proc(buf, buf, sizeof(buf));
106 /* support app launched by shell script*/
107 if (strncmp(buf, BINSH_NAME, BINSH_SIZE) == 0)
109 iterfunc(dentry->d_name, &buf[BINSH_SIZE + 1],
112 pid = iterfunc(dentry->d_name, buf, priv);
124 char *__proc_get_cmdline_bypid(int pid)
126 char buf[MAX_LOCAL_BUFSZ];
129 snprintf(buf, sizeof(buf), "/proc/%d/cmdline", pid);
130 ret = __read_proc(buf, buf, sizeof(buf));
134 /* support app launched by shell script*/
135 if (strncmp(buf, BINSH_NAME, BINSH_SIZE) == 0)
136 return strdup(&buf[BINSH_SIZE + 1]);
141 static inline int __get_pgid_from_stat(int pid)
143 char buf[MAX_LOCAL_BUFSZ];
152 snprintf(buf, sizeof(buf), "/proc/%d/stat", pid);
153 ret = __read_proc(buf, buf, sizeof(buf));
157 for (i = 0; i < (ret - 1); i++) {
160 if (count == PROC_STAT_GID_POS - 1)
162 else if (count == PROC_STAT_GID_POS) {
169 if (count == PROC_STAT_GID_POS)
177 int __proc_iter_pgid(int pgid, int (*iterfunc) (int pid, void *priv),
181 struct dirent *dentry;
185 dp = opendir("/proc");
190 while ((dentry = readdir(dp)) != NULL) {
191 if (!isdigit(dentry->d_name[0]))
194 _pgid = __get_pgid_from_stat(atoi(dentry->d_name));
196 ret = iterfunc(atoi(dentry->d_name), priv);