test structure too
[tridge/junkcode.git] / killbysubdir.c
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5 #include <dirent.h>
6 #include <sys/stat.h>
7 #include <string.h>
8 #include <signal.h>
9 #include <ctype.h>
10
11 int main(int argc, char *argv[])
12 {
13         char *directory;
14         DIR *d;
15         struct dirent *de;
16         char buf[PATH_MAX];
17         size_t directory_len;
18
19         if (argc < 2) {
20                 fprintf(stderr,"%s: <directory>\n", argv[0]);
21                 exit(1);
22         }
23         
24         directory = argv[1];
25
26         /* make it absolute */
27         if (directory[0] != '/') {
28                 char *cwd = getcwd(buf, sizeof(buf));
29                 if (cwd == NULL) {
30                         perror("cwd");
31                         exit(1);
32                 }
33                 asprintf(&directory, "%s/%s", cwd, directory);
34         }
35
36         /* resolve links etc */
37         directory = realpath(directory, buf);
38
39         if (directory == NULL) {
40                 perror("realpath");
41                 exit(1);
42         }
43
44         directory_len = strlen(directory);
45         
46         d = opendir("/proc");
47         if (d == NULL) {
48                 perror("/proc");
49                 exit(1);
50         }
51
52         while ((de = readdir(d))) {
53                 const char *name = de->d_name;
54                 char *cwd_path, *real_cwd;
55                 char cwd[PATH_MAX], buf2[PATH_MAX];
56                 ssize_t link_size;
57
58                 if (!isdigit(name[0])) continue;
59                 asprintf(&cwd_path, "/proc/%s/cwd", name);
60                 link_size = readlink(cwd_path, cwd, sizeof(cwd));
61                 free(cwd_path);
62                 if (link_size == -1 || link_size >= sizeof(cwd)) {
63                         continue;
64                 }
65
66                 real_cwd = realpath(cwd, buf2);
67                 if (real_cwd == NULL) {
68                         continue;
69                 }
70
71                 if (strncmp(directory, real_cwd, directory_len) == 0 &&
72                     (real_cwd[directory_len] == 0 || real_cwd[directory_len] == '/')) {
73                         /* kill it! */
74                         printf("Killing process %s\n", name);
75                         kill(atoi(name), SIGKILL);
76                 }
77                 
78         }
79         
80         return 0;
81 }