![](/img/trans.png)
[英]What is the proper way to execute a complex shell command within C++?
[英]What is the safe way of get the return status from an executed shell command in c++
由于cstdlib
中的函数std::system(const char* command)
不能保证将从shell返回正确的返回状态 ,那么我如何使用c / c ++在shell中运行命令并保证将给出我正确的回报价值?
以我为例,我使用以下命令运行:
bool is_process_running(std::string p_name){
std::string command_str= "ps aux | grep '" + p_name + "' | egrep -v '(grep|bash)'";
int result(0);
result= system(command_str.c_str());
return result == 0;
}
例如,如果我运行ps aux | grep 'my_process' | egrep -v '(grep|bash)'
ps aux | grep 'my_process' | egrep -v '(grep|bash)'
ps aux | grep 'my_process' | egrep -v '(grep|bash)'
直接进入终端,然后echo $?
,我看到它返回0
因为my_process
正在运行,而当我使用未运行的进程时也返回1
。 但是,上面的代码返回一个不同的值。 当我在CentOs 6中进行测试时,该代码曾经可以工作,但是现在在CentOs 7中不再起作用。 那么,我可以使用什么来运行shell命令并获得正确的结果呢?
我还找到了使用pidof
命令的解决方案,但是我不能使用它,因为pidof不会考虑传递给my_process
的参数,因为我有许多该过程的实例,每个实例都有不同的参数,因此我不需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.