简体   繁体   中英

How do I call an executable from a C program (using winapi)?

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.

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);

有关如何执行Windows程序并捕获其输出的经典资源是MSDN上的这篇文章 -实际上,它并不像看起来那样复杂。

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM