6a1d059be4c317a1a3bb70276ef4e0cc213898ef
[tools.git] / tools / spawnhunter.c
1 // Try to print the cmdlines of all process spawns by polling /proc.
2
3 #include <unistd.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <fcntl.h>
7 #include <dirent.h>
8 #include <stdio.h>
9
10
11 static unsigned int active[65536];
12
13 // assumes that *str can't be empty
14 static int str_to_int(char *str) {
15   unsigned int res = 0;
16   while (1) {
17     if (*str < '0' || *str > '9') return -1;
18     res += *str - '0';
19     str++;
20     if (*str == '\0') return res;
21     res *= 10;
22   }
23 }
24
25 int main(int argc, char *argv[]) {
26   for (int i=0; i<65536; i++) {
27     active[i] = 0;
28   }
29   
30   chdir("/proc");
31   DIR *dir = opendir(".");
32   unsigned int cycle = 2, lastcycle;
33   while (1) {
34     lastcycle = cycle-1;
35     struct dirent *dent;
36     char path[5+1+7+1];
37     while ((dent = readdir(dir)) != NULL) {
38       int name_id = str_to_int(dent->d_name);
39       if (name_id < 0 || name_id > 65535) continue;
40       if (active[name_id] != lastcycle) {
41         sprintf(path, "%s/cmdline", dent->d_name);
42         int fd = open(path, O_RDONLY);
43         if (fd != -1) {
44           char cmdline[65536];
45           int cmdline_len = read(fd, cmdline, 65536);
46           if (cmdline_len != -1) {
47             write(1, cmdline, cmdline_len);
48             write(1, "\n", 1);
49           }
50           close(fd);
51         }
52       }
53       active[name_id] = cycle;
54     }
55     rewinddir(dir);
56     cycle++;
57   }
58 }