How to convert signal name (string) to signal code

2020-02-12 05:21发布

I am writing a program that reads the name of the signal (e.g. SIGSTOP, SIGKILL etc) as a string from the command line and calls the kill() system call to send the signal. I was wondering if there is a simple way to convert the string to signal codes (in signal.h).

Currently, I'm doing this by writing my own map that looks like this:

signal_map["SIGSTOP"] = SIGSTOP;
signal_map["SIGKILL"] = SIGKILL;
....

But its tedious to write this for all signals. So, I was looking for a more elegant way, if it exists.

3条回答
Animai°情兽
2楼-- · 2020-02-12 06:00

Using C++0x you can use initializer lists to make this more simple:

const std::map<std::string, signal_t> signal_map{ 
   {"SIGSTOP", SIGSTOP },
   {"SIGKILL", SIGKILL },
   ... 
};

This get's you the map at less code to write. If you want to you could also some preprocessor magic to get the code even simpler and avoid writing the name multiple times. But most often abusing the preprocessor just leads to less usable code not better code. (Note that preprocessor magic can still be used if you decide not to use C++0x and keep your way).

查看更多
男人必须洒脱
3楼-- · 2020-02-12 06:04

You can use a command line like this

kill -l \
        | sed 's/[0-9]*)//g' \
        | xargs -n1 echo \
        | awk '{ print "signal_map[\"" $0 "\"] = " $0 ";" }'

It will write your map for you.

查看更多
姐就是有狂的资本
4楼-- · 2020-02-12 06:17

Not sure if that is what you are loking for, but: strerror() converts a error code to the error message, similar strsignal() converts a signal to the signal message.

fprintf(stdout, "signal 9: %s\n", strsignal(9));
fprintf(stdout, "errno 60: %s\n", strerror(60));

Output:
signal 9: Killed
errno 60: Device not a stream
查看更多
登录 后发表回答