Alex Rivera | Logout

Capture Output of Spawned Process to string

Asked 2013-01-03T20:57:51.760
12

Background:


I'm working on a program that needs to be able to capture the stdout, stderr and return values of a program. Ideally, I would like to capture these in a string that I store inside of my object that holds details of the process. I currently have some code that works by saving the output into a file using some (in my opinion) archaic C file handle magic. Any time I want to output the results, I open up that file and I print the contents.

Sometimes (when a process I spawn is left running) the next execution of my executable will break down because it cannot open the file for writing.

Problem Statement:


I'm looking for a way to save the output from stdout of a created process in windows to one string and the stderr to another in a safer, more modern fashion. That way I could print those contents any time I feel like outputting the result of each created process.

My ugly code:


main chunk-

    int stdoutold = _dup(_fileno(stdout)); //make a copy of stdout
    int stderrold = _dup(_fileno(stdout)); //make a copy of stderr
    FILE *f; 

    if(!fopen_s(&f, "name_of_my_file", "w")){ //make sure I can write to the file
        _dup2(_fileno(f), _fileno(stdout)); //make stdout point to f
        _dup2(_fileno(f), _fileno(stderr)); //make stderr point to f

        fork("command_I_want_to_run", &pi); //run my fake fork (see below)
    }
    else{
        ...//error handling
    }
    _close(_fileno(stdout)); //close tainted stdout
    _close(_fileno(stderr)); //close tainted stderr
    _close(_fileno(f)); //close f
    _dup2(stdoutold, _fileno(stdout)); //fix stdout
    _dup2(stderrold, _fileno(stderr)); //fix stderr

fork- (you can think of this as just CreateProcess, but just in case anyone needs to see what happens he

Edit
Report

1 Answer

3

You'll have to use pipes to capture the contents of your process's stdout stream. There's an elaborate example on MSDN on how to accomplish this:

MSDN: Creating a Child Process with Redirected Input and Output

answered 2013-01-03T22:10:46.503

Your Answer