views:

84

answers:

5

CreateProcess() came up a few times searching google....
Is it OK to assume this is the safest and most efficient method?
If so, I would like to use the output of the called process.
How do I know it has completed before continuing on in the C program?

Thanks.

+1  A: 

Depends on how you measure efficiency. system() is programmer efficient.

Also see exec() and its many brothers.

wallyk
+1  A: 

CreateProcess() is a fairly low-level function for spawning subprocesses and may not be the most convenient option. For a C program where you need to read the output, consider popen() (note that the MS CRT places an underscore before its name):

FILE *f = _popen("dir", "r");
char buf[1000];
while (fgets(buf, sizeof(buf), f)) {
    // .. process output using stdio functions
}
_pclose(f);
Greg Hewgill
popen() will not work from a GUI ap, only from a console. And please don't suggest while (!feof(f)) { - it's misused enough as it is.
anon
I change the use of feof.
Greg Hewgill
From MSDN "If used in a Windows program, the _popen function returns an invalid file pointer that will cause the program to hang indefinitely. _popen works properly in a Console application." See http://msdn.microsoft.com/en-us/library/96ayss4b%28VS.71%29.aspx
anon
+2  A: 

ShellExecute Can be used to create a process, its a more convenient way to pass arguments.

But if you want to use the output of the process then CreateProcess is probably your best bet

With CreateProcess you can pass a STARTUPINFO structure that can be used to pass a file pipe handle to Standard Out of the process.

CreateProcess will return a PROCESS_INFORMATION structure containing a HANDLE to the created process. That handle will become signalled when the process exits.

So You can WaitForSingleObject on the process handle to wait for the output to be complete.

Don't forget to CloseHandle on the process handle and thread handle when you are done.

John Knoeller
If the process you want to start requires elevation (or Vista/7 automatically thinks it does, because of its filename or another heuristic) CreateProcess will fail and you'll need to handle that specific error. See http://msdn.microsoft.com/en-us/library/bb756945.aspx. ShellExecute or ShellExecuteEx are easiest, and the second lets you get process information that I think includes a process handle you can use as John describes.
David M
+1  A: 

The classic source for how to execute a Windows program and catch its output is this article on MSDN - it's actually not as complicated as it looks.

anon
+1  A: 

If you need full control (change std in/out etc), CreateProcess is your best option. If you are executing something specified by the user, you really need to use ShellExecute[Ex] since CreateProcess will fail for applications that require UAC elevation (ShellExecuteEx is also able to give you a handle to the child process when you start applications)

Anders