C/C++ launch a subprocess and get its output

This is an usage sample of how to call a sub-process and get its screen output.


1. main.cpp

2. sub.cpp


main will call sub-process sub, and get all its screen output.


g++ sub.cpp -o sub

g++ main.cpp -o main


case 1:

$ main 
Hello test stderr
Bye test stderr
line is [Hello test stdout]
line is [Bye test stdout]

The stdout output can be caught by main process, but not stderr output.


case 2: redirect stderr to stdout

$ main 
line is [Hello test stderr]
line is [Bye test stderr]
line is [Hello test stdout]
line is [Bye test stdout]



Appendix

sub.cpp

$ cat sub.cpp 
#include <string>
#include <iostream>

int main(int argc, char * argv[]) {
    fprintf(stdout, "Hello %s stdout\n", argc > 1 ? argv[1] : argv[0]);
    fprintf(stdout, "Bye %s stdout\n", argc > 1 ? argv[1] : argv[0]);
    fprintf(stderr, "Hello %s stderr\n", argc > 1 ? argv[1] : argv[0]);
    fprintf(stderr, "Bye %s stderr\n", argc > 1 ? argv[1] : argv[0]);
    return 1;
}


main.cpp

$ cat main.cpp 
#include <sys/types.h>
#include <sys/wait.h>

#include <string>
#include <iostream>

int main(int argc, char * argv[]) {
    std::string param = "test";
    std::string cmd = "sub " + param;
    //Or if you need both stdout and stderr
    //std::string cmd = "sub " + param + " 2>&1";
    FILE * fp = popen(cmd.c_str(), "r");
    if (fp != NULL) {
        char line[1024] = { '\0' };
        while (fgets(line, 1024, fp) != NULL) {
            char * pos = NULL;
            if ((pos = strchr(line, '\n')) != NULL) {
                // remove the newline char at the end
                *pos = '\0';
            }
            std::cout << "line is [" << line << "]" << std::endl;
            memset(line, '\0', 1024);
        }
        pclose(fp);
    }

    return 0;
}


Because library function popen can only give us a file handle on a process' stdout, not stderr; however we can redirect stdout and stderr.


The end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值