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

C++ Read Continous Command Output stream like tcpdump

我想从 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

的第一行输出

我不想Write to file and read again关注。 使 tcpdump -i any -v -w myfile 将其写入文件并连续读取

尝试这样的事情:

#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;
}

联机帮助页中的一条注释

Note that output popen() streams are block buffered by default.

所以你会得到一些延迟和大块的结果,而不是逐行。