popen函数

目的

开发过程中获取某个可执行文件的打印结果或者获取某个shell命令的打印结果

原理

FILE * popen ( const char * command , const char * type );
int pclose ( FILE * stream );

popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。pclose() 函数关闭标准 I/O流,等待命令执行结束,然后返回 shell 的终止状态。如果 shell 不能被执行,则 pclose() 返回的终止状态与 shell 执行 exit 一样。

Linux代码

#include<iostream>
#include<stdio.h>
#include<string.h>
 
using namespace std;
int main()
{
    FILE *fp = NULL;
    char cmd[1024];
    char buf[1024];
    char result[4096];
    sprintf(cmd, "pwd");
    if( (fp = popen(cmd, "r")) != NULL)
    {
        while(fgets(buf, 1024, fp) != NULL)
        {
            strcat(result, buf);
        }
        pclose(fp);
        fp = NULL;
    }
    cout<<"result:"<<result<<endl;
    return 0;
}

运行结果

image

windows代码

#include<iostream>
#include<cstdio>
#include<string>

using namespace std;
int main()
{
    FILE* fp = NULL;
    char cmd[1024];
    char buf[1024];
    char result[4096] = {};
    sprintf_s(cmd, "dir");
    cout << "cmd:" << cmd << endl;
    if ((fp = _popen(cmd, "r")) != NULL)
    {
        while (fgets(buf, 1024, fp) != NULL)
        {
            strcat_s(result,sizeof(result), buf);
        }
        _pclose(fp);
        fp = NULL;
    }
    cout << "result:" << result << endl;
    return 0;
}

运行结果

image

posted @ 2024-07-01 21:07  bbkkp  阅读(2)  评论(0编辑  收藏  举报