Since the function std::system(const char* command)
from cstdlib
doesn't guarantee that will return the correct return status from the shell, then how can I run a command in shell using c/c++ and have a guarantee that will give me the right return value?
In my case, for example, I ran a command with:
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;
}
If I run, for example, ps aux | grep 'my_process' | egrep -v '(grep|bash)'
directly into the terminal and after that echo $?
, I see it returning 0
because my_process
is running and also returning 1
when I use a non running process. But, the code above returns a different value. This code used to work when I tested in CentOs 6 but now in CentOs 7 doesn't work anymore. So, what can I use to run the shell command and get the correct result?
I also found a solution using pidof
command but I can't use this because pidof doesn't consider the parameters passed to my_process
which I need since I have many instances of this process each with different arguments.