linux c执行shell命令并获取返回字符串

int DepthCamera::exec_cmd_using_popen(char const* cmd, QStringList& res_vec)
{
    if (cmd == NULL)
    {
        printf("popen cmd is NULL\n");
        return 1;
    }
    char tmp[1024];
    FILE* fp = popen(cmd, "r");
    if (NULL == fp)
    {
        printf("exec cmd: %s failed, err: %s\n", cmd,strerror(errno));
        return 1;
    }
    while (fgets(tmp, 1024, fp) != NULL)
    {
        if (tmp[strlen(tmp) - 1] == '\n')
        {
            tmp[strlen(tmp) - 1] = '\0'; //去除换行符
        }
        res_vec.push_back(tmp);
    }
    printf("exec cmd: %s ,success\n", cmd);

    pclose(fp);
    return 0;
}

你可能感兴趣的:(linux)