如何从 C 程序调用可执行文件(使用 winapi)?
CreateProcess() 出现了几次搜索谷歌....
可以假设这是最安全、最有效的方法吗?
如果是这样,我想使用被调用进程的输出。
在继续 C 程序之前,我如何知道它已经完成?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
ShellExecute 可用于创建进程,这是传递参数的更方便的方式。
但是,如果您想使用进程的输出,那么
CreateProcess
可能是您最好的选择使用
CreateProcess
您可以传递 STARTUPINFO 结构,可用于将文件管道句柄传递到进程的标准输出。CreateProcess
将返回 PROCESS_INFORMATION< /a> 结构体包含已创建进程的句柄。当进程退出时,该句柄将发出信号。因此,您可以在进程句柄上WaitForSingleObject等待输出完成。
完成后,不要忘记在进程句柄和线程句柄上
CloseHandle
。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 betWith
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.取决于你如何衡量效率。
system()
程序员效率高。另请参阅
exec()
和它的许多兄弟。Depends on how you measure efficiency.
system()
is programmer efficient.Also see
exec()
and its many brothers.CreateProcess() 是一个用于生成子进程的相当低级的函数,可能不是最方便的选项。对于需要读取输出的 C 程序,请考虑
popen()
(请注意,MS CRT 在其名称前添加下划线):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, considerpopen()
(note that the MS CRT places an underscore before its name):有关如何执行 Windows 程序并捕获其输出的经典来源是 MSDN 上的这篇文章 - 实际上并不像看起来那么复杂。
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.
如果您需要完全控制(更改标准输入/输出等),CreateProcess 是您的最佳选择。如果您正在执行用户指定的操作,则确实需要使用 ShellExecute[Ex],因为对于需要 UAC 提升的应用程序,CreateProcess 将会失败(当您启动应用程序时,ShellExecuteEx 还能够为您提供子进程的句柄) )
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)