美文网首页
Linux popen执行bash命令并获取返回字符串

Linux popen执行bash命令并获取返回字符串

作者: linanwx | 来源:发表于2017-11-08 15:22 被阅读0次

system命令返回值是个整型,很难判断具体情况是否正确。可以通过popen来执行bash命令,并获取返回值。注意popen获取的字符串返回值是标准输出,如需获取错误输出内容需要将错误输出重定向至标准输出中。

void system_cmd(const char * command, char * result)
{
    FILE *fpRead;
    fpRead = popen(command, "r");
    char buf[1024] = {0};
    memset(buf,'\0',sizeof(buf));
    while(fgets(buf,1024-1,fpRead)!=NULL)
    { 
        if (buf[strlen(buf) - 1] == '\n') {
            buf[strlen(buf) - 1] = '\0'; //去除换行符
        }
        strcpy(result, buf);
    }
    if(fpRead!=NULL)
        pclose(fpRead);
}

调用示例:

    char pid[10]={0};
    system_cmd("pgrep bash", pid);

相关文章

网友评论

      本文标题:Linux popen执行bash命令并获取返回字符串

      本文链接:https://www.haomeiwen.com/subject/brkbsxtx.html