comparison lib/lib.c @ 475:1fb149e75ebf

Add killall by Andreas Heck, and factor out common pid code to lib.h.
author Rob Landley <rob@landley.net>
date Sat, 18 Feb 2012 15:12:41 -0600
parents 41b5ac08208f
children f0b07ce5f125
comparison
equal deleted inserted replaced
474:d76583999029 475:1fb149e75ebf
807 if (tolower(*buf) == 'y') return 1; 807 if (tolower(*buf) == 'y') return 1;
808 if (tolower(*buf) == 'n') return 0; 808 if (tolower(*buf) == 'n') return 0;
809 } 809 }
810 return def; 810 return def;
811 } 811 }
812
813 // Execute a callback for each PID that matches a process name from a list.
814 int for_each_pid_with_name_in(char **names,
815 void (*callback) (const char *pid)) {
816 #define PATH_LEN 64
817
818 DIR *dp;
819 struct dirent *entry;
820 FILE *fp;
821 int n, pathpos;
822 char cmd[PATH_MAX];
823 char path[PATH_LEN];
824 char **curname;
825
826 dp = opendir("/proc");
827 if (!dp) {
828 perror("opendir");
829 return 1;
830 }
831
832 while ((entry = readdir(dp))) {
833 if (!isdigit(entry->d_name[0])) continue;
834 strcpy(path, "/proc/");
835 pathpos = 6;
836
837 if (pathpos + strlen(entry->d_name) + 1 > PATH_LEN) continue;
838
839 strcpy(&path[pathpos], entry->d_name);
840 pathpos += strlen(entry->d_name);
841
842 if (pathpos + strlen("/cmdline") + 1 > PATH_LEN) continue;
843 strcpy(&path[pathpos], "/cmdline");
844
845 fp = fopen(path, "r");
846 if (!fp) {
847 perror("fopen");
848 continue;
849 }
850
851 n = fread(cmd, 1, PATH_MAX, fp);
852 fclose(fp);
853 if (n == 0) continue;
854
855 for (curname = names; *curname; curname++) {
856 if (strcmp(basename(cmd), *curname) == 0) {
857 callback(entry->d_name);
858 }
859 }
860 }
861
862 closedir(dp);
863
864 return 0;
865 #undef PATH_LEN
866 }