c++: subprocess output to stdin

☆樱花仙子☆ 提交于 2019-11-28 03:08:07

问题


Suppose I want to call a subprocess from within my program, and I want to read the output from that subprocess into my program.

Here is a trivial way to do that:

//somefile.cpp
system("sub_process arg1 arg2 -o file.out");
           //call the subprocess and have it write to file
FILE *f = std::fopen("file.out", "r");
//.... and so on

We all know that i/o operations are computationally slow. To speed this up, I would like to skip the write-to-file-then-read-from-file step, and instead redirect the output of this sub-process directly into stdin (or some other stream)

How would I do this? How do I skip the i/o operation?

Note: many programs spit out some diagnostic stuff into stdout while they run, and write a clean version of the output to stdout (ex: stdout: "step1...done, step2...done, step3..done" -o file-out: "The magic number is: 47.28"), so ignoring the "-o " argument and trusting that output will be automatically re-directed to stdout isn't necessarily helpful...

Thanks to all in advance.


回答1:


Using popen skips the file, and gets you command's output through an in-memory buffer.

#include <iomanip>
#include <iostream>
using namespace std;
const int MAX_BUFFER = 255;
int main() {
    string stdout;
    char buffer[MAX_BUFFER];
    FILE *stream = popen("command", "r");
    while ( fgets(buffer, MAX_BUFFER, stream) != NULL )
        stdout.append(buffer);
    pclose(stream);
    cout << endl << "output: " << endl << stdout << endl;
}



回答2:


If you happen to be on windows :

follow this : http://support.microsoft.com/kb/190351

It describes it better than I ever would. You can redirect everything, everywhere.




回答3:


The best thing to do is open the shell command using popen(). This allows you to pass a command and get back a FILE* pointer to the output. See http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/FUNCTIONS/popen.html



来源:https://stackoverflow.com/questions/8438277/c-subprocess-output-to-stdin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!