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

╄→尐↘猪︶ㄣ 提交于 2019-11-29 10:25:36

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

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.

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

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