Linux系统上的popen()库函数

摘自:https://www.cnblogs.com/yuguangyuan/p/9439225.html

popen可以是系统命令,也可以是自己写的程序a.out。 假如a.out就是打印 “hello world“

在代码中,想获取什么,都可以通过popen获取。

比如获取ls的信息,

比如获取自己写的程序的内容:“hello world” 。

 

https://www.cnblogs.com/sylar5/p/6644870.html

 

在 c/c++ 程序中,可以使用 system()函数运行命令行命令,但是只能得到该命令行的 int 型返回值,并不能获得显示结果。例如system(“ls”)只能得到0或非0,如果要获得ls的执行结果,则要通过管道来完成的。首先用popen打开一个命令行的管道,然后通过fgets获得该管道传输的内容,也就是命令行运行的结果。

在linux上运行的例子如下:

void executeCMD(const char *cmd, char *result)   
{   
    char buf_ps[1024];   
    char ps[1024]={0};   
    FILE *ptr;   
    strcpy(ps, cmd);   
    if((ptr=popen(ps, "r"))!=NULL)   
    {   
        while(fgets(buf_ps, 1024, ptr)!=NULL)   
        {   
           strcat(result, buf_ps);   
           if(strlen(result)>1024)   
               break;   
        }   
        pclose(ptr);   
        ptr = NULL;   
    }   
    else  
    {   
        printf("popen %s error\n", ps);   
    }   
}

在这段代码中,参数cmd为要执行的命令行,result为命令行运行结果。输入的cmd命令最好用... 2>&1 的形式,这样将标准错误也读进来。

一个完整的例子是:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
        FILE* fp = NULL;
        char cmd[512];
        sprintf(cmd, "pwd 2>/dev/null; echo $?");
        if ((fp = popen(cmd, "r")) != NULL)
        {
                fgets(cmd, sizeof(cmd), fp);
                                pclose(fp);
        }

                  //0 成功, 1 失败
        printf("cmd is %s\n", cmd);

        return 0;
}

 

posted @ 2020-03-21 18:35  LiuYanYGZ  阅读(386)  评论(0编辑  收藏  举报