android 反混淆配置:popen——C程序中获取Shell命令的输出

来源:百度文库 编辑:中财网 时间:2024/04/29 09:30:05
以前在C程序中习惯用system来调用执行shell命令,但是这样有个缺点,就是只能得到执行的shell命令的返回值,如果想得到其输出,只能通过一些间接的方法,比如修改shell命令让它的输出重定向到一文件中,然后c程序再从该文件获取。这样的缺点是需要磁盘操作,降低了程序的执行效率。
如果用popen即可解决这个问题。
#include
FILE *popen(const char *cmdstring, const char *type) ;
函数popen 先执行fork,然后调用exec以执行cmdstring,并且返回一个标准I/O文件指针。
如果type是"r",则文件指针连接到cmdstring的标准输出;
如果type是"w",则文件指针连接到cmdstring的标准输入。
下面的例子用wget或curl从网上抓取一个网页,然后把该网页输出到终端:
#include stdlib.h>
int main()
{
    FILE *fp;
    if ((fp = popen("wget www.baidu.com -O -", "r")) == NULL) {//用“curl www.baidu.com”也是一样的
        perror("popen failed");
        return -1;
    }
    char buf[256];
    while (fgets(buf, 255, fp) != NULL) {
           printf("%s", buf);
    }
    if (pclose(fp) == -1) {
        perror("pclose failed");
        return -2;
    }
    return 0;
}
感谢xuxingye和
keensword007