![](/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.