C++调用linux命令并获取返回值

qt中封装了相关的方法, 但是因为我的命令中用到了管道命令, 出现了非预期结果, 所有改用了linux系统原生的方法。

下边是一个判断某进程是否存在的例子。

#include <stdlib.h>

bool IsProcessOn()
{
    string check_command = " ps -ef | grep -w process_name | grep -v grep | wc -l ";
    char return_value[150];
    int count = 0;
    FILE* ptr = NULL;
    if((ptr = popen(check_command.c_str(), "r")) == NULL)
    {
        return false;
    }
    memset(return_value, 0, sizeof(return_value));
    if((fgets(return_value, sizeof(return_value),ptr))!= NULL)
    {
        count = atoi(return_value);
    }
    pclose(ptr);
    if(count <= 0)
    {
        return false;
    }
    return true;
}

猜你喜欢

转载自www.cnblogs.com/devil-shadow/p/11844134.html