Add name2sig() and simplify kill(1)

This commit is contained in:
sin 2014-11-11 16:27:17 +00:00
parent 88f26b222b
commit e0b0741ba1

54
kill.c
View File

@ -23,6 +23,7 @@ struct {
}; };
const char *sig2name(int); const char *sig2name(int);
int name2sig(const char *);
static void static void
usage(void) usage(void)
@ -54,14 +55,9 @@ main(int argc, char *argv[])
} else if (argv[0][0] == '-' && isdigit(argv[0][1])) { } else if (argv[0][0] == '-' && isdigit(argv[0][1])) {
/* handle XSI extension -signum */ /* handle XSI extension -signum */
errno = 0; errno = 0;
sig = strtol(&argv[0][1], &end, 0); sig = strtol(&argv[0][1], &end, 10);
if (*end != '\0' || errno != 0) if (*end != '\0' || errno != 0)
eprintf("%d: bad signal number\n", sig); eprintf("%s: bad signal number\n", &argv[0][1]);
for (i = 0; i < LEN(sigs); i++)
if (sigs[i].sig == sig || sig == 0)
break;
if (i == LEN(sigs))
eprintf("%d: bad signal number\n", sig);
argc--; argc--;
argv++; argv++;
} else if (strcmp(argv[0], "-l") == 0) { } else if (strcmp(argv[0], "-l") == 0) {
@ -74,16 +70,10 @@ main(int argc, char *argv[])
} else if (argc > 1) } else if (argc > 1)
usage(); usage();
errno = 0; errno = 0;
sig = strtol(argv[0], &end, 0); sig = strtol(argv[0], &end, 10);
if (*end == '\0' && errno == 0) { if (*end != '\0' || errno != 0)
name = sig2name(sig); eprintf("%s: bad signal number\n", argv[0]);
if (!name) puts(sig2name(sig));
eprintf("%d: bad signal number\n", sig);
else
puts(name);
} else {
eprintf("%s: bad signal name\n", argv[0]);
}
exit(0); exit(0);
} else { } else {
if (strcmp(argv[0], "-s") == 0) { if (strcmp(argv[0], "-s") == 0) {
@ -96,18 +86,7 @@ main(int argc, char *argv[])
/* assume XSI extension -signame */ /* assume XSI extension -signame */
name = &argv[0][1]; name = &argv[0][1];
} }
if (strcmp(name, "0") == 0) { sig = strcmp(name, "0") == 0 ? 0 : name2sig(name);
sig = 0;
} else {
for (i = 0; i < LEN(sigs); i++) {
if (strcasecmp(sigs[i].name, name) == 0) {
sig = sigs[i].sig;
break;
}
}
if (i == LEN(sigs))
eprintf("%s: bad signal name\n", name);
}
argc--; argc--;
argv++; argv++;
} }
@ -117,7 +96,7 @@ main(int argc, char *argv[])
for (; argc; argc--, argv++) { for (; argc; argc--, argv++) {
errno = 0; errno = 0;
pid = strtol(argv[0], &end, 0); pid = strtol(argv[0], &end, 10);
if (*end == '\0' && errno == 0) { if (*end == '\0' && errno == 0) {
if (kill(pid, sig) < 0) { if (kill(pid, sig) < 0) {
weprintf("kill %d:", pid); weprintf("kill %d:", pid);
@ -142,5 +121,20 @@ sig2name(int sig)
for (i = 0; i < LEN(sigs); i++) for (i = 0; i < LEN(sigs); i++)
if (sigs[i].sig == sig) if (sigs[i].sig == sig)
return sigs[i].name; return sigs[i].name;
eprintf("%d: bad signal number\n", sig);
/* unreachable */
return NULL; return NULL;
} }
int
name2sig(const char *name)
{
size_t i;
for (i = 0; i < LEN(sigs); i++)
if (strcasecmp(sigs[i].name, name) == 0)
return sigs[i].sig;
eprintf("%s: bad signal name\n", name);
/* unreachable */
return -1;
}