popen函数代替system函数

system()函数的原型为:

int system(const char *command);

函数的返回值表示system()函数调用的执行结果,成功返回0,失败返回-1并设置errno为错误代码。需要注意的是该函数并不能获取command命令的执行结果。

tmp.txt的内容为:

helloworld
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

int main(void)
{
    int ret = system("cat tmp1.txt");   //不存在tmp1.txt
    if (ret < 0)
        perror("system");

    system("cat tmp.txt");  
    if (ret < 0)
        perror("system");

    return 0;
}

运行:
这里写图片描述

要想在代码中获取command命令的执行结果,可以通过popen函数:

int main(void)
{
    FILE* fp = NULL;
    char buf[1024] = {'\0'};
    fp = popen("cat tmp.txt", "r");
    fgets(buf, 1024, fp);
    printf("buf: %s\n", buf);

    pclose(fp);

    return 0;
}

运行:
这里写图片描述
可见popen()函数是将标准输出重定位到fp中,然后通过读取fp就可以获取command命令执行的输出结果。需要注意,command命令若执行失败,其错误信息从标准错误输出,所以不能通过fp指针获取错误输出结果。

fp = popen("cat tmp1.txt", "r");    //tmp1.txt在文件中并不存在
fgets(buf, 1024, fp);
printf("buf: %s\n", buf);

运行:
这里写图片描述
解决办法是在command中将标准错误输出重定向到标准输出中,即命令上加上”2>&1

fp = popen("cat tmp1.txt 2>&1", "r");   //tmp1.txt在文件中并不存在
fgets(buf, 1024, fp);
printf("buf: %s\n", buf);

运行:
这里写图片描述
这样就可以拿到命令正确执行和执行出错的结果了。

猜你喜欢

转载自blog.csdn.net/qq_29344757/article/details/80110250
今日推荐