How to convert signal name (string) to signal code?

天大地大妈咪最大 提交于 2019-11-28 03:37:17

问题


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.


回答1:


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



回答2:


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.




回答3:


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).



来源:https://stackoverflow.com/questions/6990093/how-to-convert-signal-name-string-to-signal-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!