8

In Windows, is there a way to launch a process in C++ and then read what it spat out into stdout when it's done? The process must be run using elevated privileges (on Vista or later) if necessary.

I'm currently using ShellExecuteEx() to launch the process and running a while-loop until GetExitCodeProcess() no longer returns STILL_ACTIVE via the lpExitCode parameter (with a WaitForSingleObject() call doing a 100 msec wait during each iteration).

2
  • Can you redirect stdout into a named pipe when launching the process? (Not a C++ developer, hence making this a comment) Nov 4, 2010 at 1:57
  • 3
    The problem is that to run an elevated process you have to use ShellExecuteEx() with the runas verb. And ShellExecuteEx() doesn't support output redirection AFAICT. Nov 4, 2010 at 2:05

4 Answers 4

3

There's no easy way to do this.

Calling ShellExecuteEx() with the runas verb sends an RPC message to the AppInfo NT Service witch then run the application from an elevated session. There's no API to easily connect the input/output of the elevated process to your application.

Thomas Hruska in his The Code Project article presents his implementation of a CreateProcessElevated() function that solves this.

Instead of running the elevated program directly CreateProcessElevated() relies on another executable that receive the name of the stdin,stdout,stderr named pipes and recreate their handles in the elevated session before calling CreateProcess().

1
  • I like the Code Project solution. Unfortunately, since it involves a separate DLL, I won't be able to use it for my particular project, which is an installer's bootstrap application. (Sigh! Back to the drawing board, I guess.)
    – RobH
    Nov 4, 2010 at 18:01
3

You should replace your use of ShellExecuteEx with CreateProcess. The lpStartupInfo argument lets the std in and std out handles of the process. Just Create an anonymous pipe using CreatePipe that you pass as the arguments. This MSDN article has an example of how to do this.

1
  • But CreateProcess() cannot be used to start an elevated process, unless the parent process also is elevated.
    – Ian Goldby
    Sep 14, 2011 at 15:08
0

You need to create a named pipe to the child process. This MSDN article explains with and has code samples.

You should be able to get it going from that.

1
  • Unfortunately, this solution uses CreateProcess() rather than ShellExecuteEx(). Jun 5, 2012 at 21:15
0

Can you not use CreateProcess/ShellExecuteEx to exec a cmd shell with stdout/stderr redirected that in turn invokes your process?

"cmd /c YourProcess.exe {parameters}" etc?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.