killall5.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /* See LICENSE file for copyright and license details. */
  2. #include <dirent.h>
  3. #include <limits.h>
  4. #include <signal.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <unistd.h>
  9. #include "proc.h"
  10. #include "queue.h"
  11. #include "util.h"
  12. struct {
  13. const char *name;
  14. int sig;
  15. } sigs[] = {
  16. #define SIG(n) { #n, SIG##n }
  17. SIG(ABRT), SIG(ALRM), SIG(BUS), SIG(CHLD), SIG(CONT), SIG(FPE), SIG(HUP),
  18. SIG(ILL), SIG(INT), SIG(KILL), SIG(PIPE), SIG(QUIT), SIG(SEGV), SIG(STOP),
  19. SIG(TERM), SIG(TSTP), SIG(TTIN), SIG(TTOU), SIG(USR1), SIG(USR2), SIG(URG),
  20. #undef SIG
  21. };
  22. struct pidentry {
  23. pid_t pid;
  24. SLIST_ENTRY(pidentry) entry;
  25. };
  26. static SLIST_HEAD(, pidentry) omitpid_head;
  27. static void
  28. usage(void)
  29. {
  30. eprintf("usage: %s [-o pid1,pid2,..,pidN] [-s signal]\n", argv0);
  31. }
  32. int
  33. main(int argc, char *argv[])
  34. {
  35. struct pidentry *pe;
  36. struct dirent *entry;
  37. DIR *dp;
  38. char *p, *arg = NULL;
  39. char *end, *v;
  40. int oflag = 0;
  41. int sig = SIGTERM;
  42. pid_t pid;
  43. size_t i;
  44. ARGBEGIN {
  45. case 's':
  46. v = EARGF(usage());
  47. sig = strtol(v, &end, 0);
  48. if (*end == '\0')
  49. break;
  50. for (i = 0; i < LEN(sigs); i++) {
  51. if (strcasecmp(v, sigs[i].name) == 0) {
  52. sig = sigs[i].sig;
  53. break;
  54. }
  55. }
  56. if (i == LEN(sigs))
  57. eprintf("%s: unknown signal\n", v);
  58. break;
  59. case 'o':
  60. oflag = 1;
  61. arg = EARGF(usage());
  62. break;
  63. default:
  64. usage();
  65. } ARGEND;
  66. SLIST_INIT(&omitpid_head);
  67. for (p = strtok(arg, ","); p; p = strtok(NULL, ",")) {
  68. pe = emalloc(sizeof(*pe));
  69. pe->pid = estrtol(p, 10);
  70. SLIST_INSERT_HEAD(&omitpid_head, pe, entry);
  71. }
  72. if (sig != SIGSTOP && sig != SIGCONT)
  73. kill(-1, SIGSTOP);
  74. if (!(dp = opendir("/proc")))
  75. eprintf("opendir /proc:");
  76. while ((entry = readdir(dp))) {
  77. if (pidfile(entry->d_name) == 0)
  78. continue;
  79. pid = estrtol(entry->d_name, 10);
  80. if (pid == 1 || pid == getpid() ||
  81. getsid(pid) == getsid(0) || getsid(pid) == 0)
  82. continue;
  83. if (oflag == 1) {
  84. SLIST_FOREACH(pe, &omitpid_head, entry)
  85. if (pe->pid == pid)
  86. break;
  87. if (pe)
  88. continue;
  89. }
  90. kill(pid, sig);
  91. }
  92. closedir(dp);
  93. if (sig != SIGSTOP && sig != SIGCONT)
  94. kill(-1, SIGCONT);
  95. return 0;
  96. }