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

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

I am currently doing this by writing my own map, which looks like this:

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

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

+6
source share
3 answers

Not sure if this is what you want, but: strerror () converts the error code into an error message, similar to strsignal () converts a signal into an alarm 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 
+14
source

You can use a command line like this

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

He will write your card for you.

+5
source

Using C ++ 0x, you can use initializer lists to make this simpler:

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

This will give you a card with less code to write. If you want, you can also use some preprocessing magic to get the code even easier and not write multiple times. But more often than not, abuse of the preprocessor simply leads to the fact that the code is less useful, and not the best code. (Note that preprocessing magic can still be used if you decide not to use C ++ 0x and continue on your way).

+1
source

Source: https://habr.com/ru/post/894594/


All Articles