CreateProcess() came up a few times searching google....
Is it OK to 开发者_如何学JAVAassume 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.
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.
Depends on how you measure efficiency. system()
is programmer efficient.
Also see exec()
and its many brothers.
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);
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.
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)
精彩评论