C++ C++;从程序参数传递的信号名
所以我遇到了一个问题,我想用main函数的参数调用我的程序(假设我这样调用它:program SIGQUIT),并在代码中把这个参数传递给kill()和signal()函数C++ C++;从程序参数传递的信号名,c++,type-conversion,signals,C++,Type Conversion,Signals,所以我遇到了一个问题,我想用main函数的参数调用我的程序(假设我这样调用它:program SIGQUIT),并在代码中把这个参数传递给kill()和signal()函数 我想问的问题是:如何从包含“SIGQUIT”的字符类型argv[2]中获取整数信号数?为什么不用字符串和相应的int构建一个查找表呢?如果您只需要在系统上定义的信号,您将需要以下内容: #include <csignal> #include <map> #include <string>
我想问的问题是:如何从包含“SIGQUIT”的字符类型argv[2]中获取整数信号数?为什么不用字符串和相应的
int
构建一个查找表呢?如果您只需要在系统上定义的信号,您将需要以下内容:
#include <csignal>
#include <map>
#include <string>
#include <iostream>
#include <cassert>
int main(int argc, char *argv[]){
// lookup table
std::map<std::string, int> lookup_table;
#define ADD_SIGNAL(X) lookup_table.insert(std::make_pair(#X,X));
// standard signals
ADD_SIGNAL(SIGABRT);
ADD_SIGNAL(SIGFPE);
ADD_SIGNAL(SIGILL);
ADD_SIGNAL(SIGINT);
ADD_SIGNAL(SIGSEGV);
ADD_SIGNAL(SIGTERM);
// implementation specific signals
#ifdef SIGKILL
ADD_SIGNAL(SIGKILL);
#endif
#ifdef SIGSTOP
ADD_SIGNAL(SIGSTOP);
#endif
// ...
#undef ADD_SIGNAL
assert(argc > 1 && "No signal");
std::string sig = argv[1];
std::map<std::string, int>::iterator it = lookup_table.find(sig);
if(it != lookup_table.end())
std::cout << "Signal " << it->first << ": " << it-> second << std::endl;
else
std::cout << "Unknown signal " << sig << std::endl;
}
请注意,n.m.的回答默认假定您使用的是
bash
作为shell-它不能与dash
甚至zsh
一起使用,因为kill-l
的输出格式不同。
kill -l | sed 's/[0-9]*)//g'
| grep -v "[+-]"
| xargs -n1 echo
| awk '{ print "#ifdef " $0 "\n\tADD_SIGNAL(" $0 ")\n#endif" }'