On 9 June 2011 16:06, Hiltjo Posthuma <hil...@codemadness.org> wrote:

> I like it, but what about -signalnumber (and maybe -signalname), I use
> -9 all the time :)

I was wondering whether to do that or not, it's pretty useful but
there's a fair bit more code. I'll leave it to cls to decide.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include "util.h"

#define LEN(x) (sizeof(x)/sizeof((x)[0]))

struct
{
	const char *name;
	int sig;
} sigs[] = {
#define SIG(n) { #n, n }
	SIG(SIGHUP),  SIG(SIGINT),  SIG(SIGQUIT), SIG(SIGTRAP),
	SIG(SIGABRT), SIG(SIGKILL), SIG(SIGUSR1), SIG(SIGSEGV),
	SIG(SIGUSR2), SIG(SIGPIPE), SIG(SIGALRM), SIG(SIGTERM),
	SIG(SIGCHLD), SIG(SIGCONT), SIG(SIGSTOP), SIG(SIGTSTP),
	SIG(SIGTTIN), SIG(SIGTTOU), SIG(SIGWINCH)
#undef SIG
};


int num(const char *s)
{
	char *end;
	int n = strtol(s, &end, 0);

	if(*end != '\0')
		eprintf("%s: not a number\n", s);

	return n;
}

int parse_sig(const char *s)
{
	int i;

	if('0' <= *s && *s <= '9')
		return num(s);

	if(strncmp(s, "SIG", 3))
		for(i = 0; i < LEN(sigs); i++)
			sigs[i].name += 3;

	for(i = 0; i < LEN(sigs); i++)
		if(!strcmp(sigs[i].name, s))
			return sigs[i].sig;

	eprintf("%s: invalid signal\n", s);
	/* unreachable */
	return -1;
}

int
main(int argc, char *argv[])
{
	int sig = SIGTERM;
	int i;

	if(argc == 1){
usage:
		eprintf("usage: %s [-s signal] [pid...]\n", argv[0]);
	}

	i = 1;
	if(argv[i][0] == '-'){
		if(!strcmp(argv[i], "-s")) {
			if(++i == argc)
				goto usage;

			sig = parse_sig(argv[i]);
		}else{
			sig = parse_sig(argv[i] + 1);
		}

		i++;
	}

	if(i == argc)
		eprintf("%s: not enough arguments\n", argv[0]);

	for(; i < argc; i++) {
		int pid = num(argv[i]);

		if(kill(pid, sig) == -1)
			eprintf("kill %d:", pid);
	}

	return 0;
}

Reply via email to