trunk 20080912
[gitenigma.git] / src / enigma_processutils.cpp
blobece20eea1290f722b2255cddf799e6b3db9279a8
1 #include <unistd.h>
2 #include <dirent.h>
3 #include <signal.h>
4 #include <sys/wait.h>
5 #include <lib/base/estring.h>
6 #include <enigma_processutils.h>
8 long *eProcessUtils::getPID(const char *procname)
10 struct dirent *entry;
11 long *pidList = (long *)malloc(sizeof(long));
13 char *name;
14 int pid, i = 0;
15 char buf[1024], cmdline[40];
16 FILE *fp;
18 DIR *dir = opendir("/proc");
19 if (dir)
21 while (1)
23 if ((entry = readdir(dir)) == NULL)
25 closedir(dir);
26 break;
29 name = entry->d_name;
31 if (!(*name >= '0' && *name <= '9'))
32 continue;
34 pid = atoi(name);
35 sprintf(cmdline, "/proc/%d/cmdline", pid);
36 if ((fp = fopen(cmdline, "r")) == NULL)
37 continue;
39 if ((fread(buf, 1, sizeof(buf) - 1, fp)) > 0)
41 if (strstr(buf, procname) != 0)
43 pidList = (long *)realloc( pidList, sizeof(long) * (i + 2));
44 pidList[i++] = pid;
47 fclose(fp);
51 pidList[i] = (i == 0) ? -1 : 0;
53 return pidList;
56 void killPID(long *pid)
58 if (*pid != -1 && *pid != 0)
60 if (kill(*pid, SIGTERM)!= 0)
61 kill(*pid, SIGKILL);
62 waitpid(*pid, 0, 0);
63 *pid = -1;
67 void eProcessUtils::killProcess(const char *procname)
69 if(strlen(procname) != 0)
71 long *pidList;
72 pidList = getPID(procname);
74 if (*pidList > 0)
76 long *pid;
77 for (pid = pidList; *pid != 0; pid++)
78 killPID(pid);
80 free(pidList);