Solved

CreateProcess and redirect to file using hStdOutput

Posted on 2006-10-30
7
6,035 Views
Last Modified: 2013-11-20
Hi Experts,
I would like to redirect the output of a command line program to a file using hStdOutput.
However, while the program happily displays its output in its dos window, the file is not written.
What am I doing wrong?

here is what I am doing:
      STARTUPINFO si;
      ZeroMemory( &si, sizeof(si) );
      si.cb = sizeof(si);
      si.dwFlags = STARTF_USESHOWWINDOW;
      si.wShowWindow = SW_SHOW;
      CFile file;
      file.Open(outFile.c_str(),CFile::modeWrite);
      ofstream out(outFile.c_str());

//Both approaches don't work
      si.hStdOutput = out;
                si.hStdOutput = file;
//ofstream is at least creating the file

      if( !CreateProcess(
            0,//nExeLoc.c_str(),            // Location of executable
            //Cannot take full path (spaces) MAybe with \"\"
            commandLine.GetBuffer(),// Command line parameters.
            NULL,           // Process handle not inheritable.
            NULL,           // Thread handle not inheritable.
            FALSE,          // Set handle inheritance to FALSE.
            0,              // No creation flags.
            NULL,           // Use parent's environment block.
            wd.GetBuffer(),        // Use parent's starting directory.
            &si,            // Pointer to STARTUPINFO structure.
            &procInfo )           // Pointer to PROCESS_INFORMATION structure.
      ) {
            //Error occured!
            return(false);
      }

This is urgent for me.
Thanks,
Jens
0
Comment
Question by:allmer
  • 2
7 Comments
 
LVL 48

Expert Comment

by:AlexFM
ID: 17832326
Instead of CFile use CreateFile function which returns HANDLE. Use this handle to fill members of STARTUPINFO structure for redirecting program output.
0
 
LVL 22

Accepted Solution

by:
mahesh1402 earned 250 total points
ID: 17832455
I think you need to specify STARTUPINFO.dwFlags = STARTF_USESTDHANDLES

As per docs :

dwFlags :
STARTF_USESTDHANDLES If this value is specified, sets the standard input of the process, standard output, and standard error handles to the handles specified in the hStdInput, hStdOutput, and hStdError members of the STARTUPINFO structure. The CreateProcess function's fInheritHandles parameter must be set to TRUE for this to work properly.

If this value is not specified, the hStdInput, hStdOutput, and hStdError members of the STARTUPINFO structure are ignored.  <==

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/startupinfo_str.asp


Here is full sample code :
How to spawn console processes with redirected standard handles : http://support.microsoft.com/kb/190351 <=======

-MAHESH
0
 
LVL 22

Expert Comment

by:mahesh1402
ID: 17832470
as per bove which means you also need STARTUPINFO.bInheritHandle = TRUE

STARTUPINFO si;

si.dwFlags = STARTF_USESTDHANDLES;
si.bInheritHandle = TRUE;

...

Refer above link for full example code.

-MAHESH
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 250 total points
ID: 17834337
AlexFM is correct about 'CreateProcess()', however some constraints have to be met regarding how to set it up. Here's a code snippet (taken from 'production' code) which does that:

    SECURITY_ATTRIBUTES sa;
    STARTUPINFO         si;
    PROCESS_INFORMATION pi;
    HANDLE              hStdOut;
    BOOL                bRes;

    sa.nLength              =   sizeof  (   SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor =   NULL;
    sa.bInheritHandle       =   TRUE;

    dwFlags =       FILE_ATTRIBUTE_NORMAL;

    hStdOut =   CreateFile  (   "c:\\test.out",
                                GENERIC_WRITE,,
                                FILE_SHARE_READ | FILE_SHARE_WRITE,
                                &sa,
                                CREATE_ALWAYS,
                                dwFlags,
                                NULL
                            );

    ZeroMemory  (   &si,    sizeof  (   STARTUPINFO));

    si.cb           =   sizeof  (   STARTUPINFO);
    si.dwFlags      =   STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    si.wShowWindow  =   SW_HIDE;
    si.hStdInput    =   NULL;
    si.hStdOutput   =   hStdOut; // output file handle
    si.hStdError    =   NULL;

    bRes    =   CreateProcess   (   "sample.exe",
                                    NULL,
                                    NULL,
                                    NULL,
                                    TRUE,
                                    NORMAL_PRIORITY_CLASS,
                                    GetEnvironmentStrings   (),
                                    "C:\\somedir",
                                    &si,
                                    &pi
                                );

    // wait with patience .....
    WaitForSingleObject (   pi.hProcess,    INFINITE);
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
repeatSeparator  java  challenge 13 56
Installing Microsoft R server on REDHAT or SUSE Linux 4 131
unable to delete all specified values regedit 38 285
move a line in eclipse 3 83
This is to be the first in a series of articles demonstrating the development of a complete windows based application using the MFC classes.  I’ll try to keep each article focused on one (or a couple) of the tasks that one may meet.   Introductio…
Introduction: Dialogs (2) modeless dialog and a worker thread.  Handling data shared between threads.  Recursive functions. Continuing from the tenth article about sudoku.   Last article we worked with a modal dialog to help maintain informat…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now