C ++读取连续命令输出流,如tcpdump

时间:2019-06-02 08:34:35

标签: c++ popen outputstream

我想从c ++程序中读取诸如tcpdump之类的命令的连续输出流。

#include <iostream>
#include <string>
#include <stdio.h>


std::string outputcmd(std::string cmd){
    std::string data;
    char singlelinedata[1024];
    FILE * streamdata;
    streamdata = popen(cmd.c_str(), "r");
    cmd.append(" 2>&1");
    std::cout << feof(streamdata);
    if(streamdata){
        while(!feof(streamdata)){
            // if(fgets(singlelinedata, 1024, streamdata)  != NULL ){
            //     data.append(singlelinedata);
            // }
            if(fread(singlelinedata, 1024, sizeof(singlelinedata)/sizeof(singlelinedata),streamdata)){
                data.append(singlelinedata);
            }
        }
        pclose(streamdata);
    }
    return data;
}

int main(){

    std::string outp;
    outp = outputcmd("sudo tcpdump -i any -v");
    std::cout << outp;
    return 0;
}

它只给我tcpdump -i any -v的第一行输出

enter image description here

我不想Write to file and read again像下面这样。 制作tcpdump -i any -v -w myfile使其记录在案并连续阅读

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

#include <iostream>
#include <string>
#include <stdio.h>


void outputcmd(std::string cmd){
    char buffer[1024];
    FILE * pipef = popen(cmd.c_str(), "r");
    if(pipef){
        while(!feof(pipef)){
            int res;
            if((res = fread(buffer, /*note order here*/ 1, sizeof(buffer), pipef)) > 0){
                std::string block(buffer, res);
                std::cout << "read from pipe: [" << block << "] size " << block.size() << std::endl;
            }
        }
        pclose(pipef);
    }
}

int main(){
    outputcmd("sudo tcpdump -i any -v");
    return 0;
}

联机帮助页上的一条笔记

  

请注意,默认情况下,输出popen()流是块缓冲的。

因此,您将获得一些延迟和大量结果,而不是逐行显示。