【问题标题】:Write a process's output to a buffer [duplicate]将进程的输出写入缓冲区[重复]
【发布时间】:2012-10-22 07:00:52
【问题描述】:

可能重复:
How to execute a command and get output of command within C++?

在我的 c++ 程序中,我正在使用 execv/system 运行一个外部程序。

我想将程序的输出重定向到我程序中的一个缓冲区,即:

char* buff[some size large enough for any possible output];
system(some program);
//THE PROGRAM I JUST RAN IS A SPECIAL BLACK BOX PROGRAM THAT RUNS
//AND PARSE AN HTTP DUMP FILE AND PRINTS IT TO THE SCREEN WHEN RUNNING
//I WANT THE OUTPUT TO GO A BUFFER IN MY PROGRAM.
//THE IDEA IS TO HAVE THE DATA OF THE OUTPUT ON THE BUFFER RATHER THAN ON A FILE

//have the buffer filled with the output of the program

谢谢:-)

【问题讨论】:

标签: c++ linux


【解决方案1】:

我不确定是否有其他方法可以做到这一点,但这就是我想到的

char* buff[some size large enough for any possible output];
system(some program >somefile.txt);  

//have the buffer filled with the output of the program
// And redirect it into a file


//Do initial validity checks and open the file



read(somefile.txt,buff,bufflen);
//Read the file

unlink somefile.txt 
//Unlink if the file is not needed

将 bufflen 替换为您要从文件中读取的字节数。

【讨论】:

  • 或者甚至只是在流中读取它并读入一个字符串,然后你不需要担心大小(如果你要写一个这样的外部文件)
【解决方案2】:

如果您想读取子进程的输出,那么(至少在 POSIX/UNIX/Linux 世界中)您应该真正考虑使用管道进行进程间通信。一个关于 Stackoverflow 的有用问题/答案以及一些好的资源的链接在这里:fork(), pipe() and exec() process creation and communication

【讨论】:

    猜你喜欢
    • 2015-08-26
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 2016-09-21
    相关资源
    最近更新 更多