ubase/killall5.c

112 lines
2.1 KiB
C
Raw Permalink Normal View History

2014-03-06 06:13:47 -05:00
/* See LICENSE file for copyright and license details. */
#include <dirent.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
2014-03-17 08:26:19 -04:00
#include <string.h>
2014-03-06 06:13:47 -05:00
#include <unistd.h>
2014-06-30 14:03:41 -04:00
2014-03-06 06:13:47 -05:00
#include "proc.h"
#include "queue.h"
2014-03-06 06:13:47 -05:00
#include "util.h"
struct {
const char *name;
int sig;
} sigs[] = {
#define SIG(n) { #n, SIG##n }
SIG(ABRT), SIG(ALRM), SIG(BUS), SIG(CHLD), SIG(CONT), SIG(FPE), SIG(HUP),
SIG(ILL), SIG(INT), SIG(KILL), SIG(PIPE), SIG(QUIT), SIG(SEGV), SIG(STOP),
SIG(TERM), SIG(TSTP), SIG(TTIN), SIG(TTOU), SIG(USR1), SIG(USR2), SIG(URG),
#undef SIG
};
struct pidentry {
2014-03-17 08:26:19 -04:00
pid_t pid;
SLIST_ENTRY(pidentry) entry;
};
static SLIST_HEAD(, pidentry) omitpid_head;
2014-03-17 08:26:19 -04:00
static void
usage(void)
{
eprintf("usage: %s [-o pid1,pid2,..,pidN] [-s signal]\n", argv0);
}
2014-03-06 06:13:47 -05:00
int
main(int argc, char *argv[])
{
struct pidentry *pe;
2014-03-06 06:13:47 -05:00
struct dirent *entry;
DIR *dp;
char *p, *arg = NULL;
2014-03-06 06:13:47 -05:00
char *end, *v;
int oflag = 0;
2014-03-06 06:13:47 -05:00
int sig = SIGTERM;
pid_t pid;
size_t i;
ARGBEGIN {
case 's':
v = EARGF(usage());
sig = strtol(v, &end, 0);
2014-07-09 11:39:32 -04:00
if (*end == '\0')
2014-03-06 06:13:47 -05:00
break;
2014-07-09 11:39:32 -04:00
for (i = 0; i < LEN(sigs); i++) {
if (strcasecmp(v, sigs[i].name) == 0) {
2014-03-06 06:13:47 -05:00
sig = sigs[i].sig;
break;
}
}
2014-07-09 11:39:32 -04:00
if (i == LEN(sigs))
2014-03-06 06:13:47 -05:00
eprintf("%s: unknown signal\n", v);
break;
2014-03-17 08:26:19 -04:00
case 'o':
oflag = 1;
arg = EARGF(usage());
break;
2014-03-06 06:13:47 -05:00
default:
usage();
} ARGEND;
SLIST_INIT(&omitpid_head);
if (oflag) {
for (p = strtok(arg, ","); p; p = strtok(NULL, ",")) {
pe = emalloc(sizeof(*pe));
pe->pid = estrtol(p, 10);
SLIST_INSERT_HEAD(&omitpid_head, pe, entry);
}
2014-03-17 08:26:19 -04:00
}
2014-03-06 06:13:47 -05:00
if (sig != SIGSTOP && sig != SIGCONT)
kill(-1, SIGSTOP);
if (!(dp = opendir("/proc")))
eprintf("opendir /proc:");
while ((entry = readdir(dp))) {
2014-03-06 10:06:47 -05:00
if (pidfile(entry->d_name) == 0)
2014-03-06 06:13:47 -05:00
continue;
pid = estrtol(entry->d_name, 10);
if (pid == 1 || pid == getpid() ||
getsid(pid) == getsid(0) || getsid(pid) == 0)
continue;
2014-03-17 08:26:19 -04:00
if (oflag == 1) {
SLIST_FOREACH(pe, &omitpid_head, entry)
if (pe->pid == pid)
2014-03-17 08:26:19 -04:00
break;
if (pe)
2014-03-17 08:26:19 -04:00
continue;
}
2014-03-06 06:13:47 -05:00
kill(pid, sig);
}
closedir(dp);
if (sig != SIGSTOP && sig != SIGCONT)
kill(-1, SIGCONT);
2014-10-02 18:45:25 -04:00
return 0;
2014-03-06 06:13:47 -05:00
}