如何使用 CreateProcess 启动外部程序并等待其结束?
解读
国内 Windows 桌面开发面试中,VB6 与 VB.NET 并存,但考点趋同:
- 必须区分“Shell 函数”与“Win32 CreateProcess”——前者只能拿到任务 ID,后者才能拿到 hProcess;
- 必须显式等待进程句柄,不能用 DoEvents 死循环,否则会被直接判负;
- 必须处理超时、返回值、错误码,体现工业级代码意识;
- 若答 VB.NET,需补充 Process 类与 Win32 的差异,展示“既懂封装也懂底层”的厚度。
一句话:面试官要的是“你能启动、能等待、能容错、能解释”。
知识点
- Win32 CreateProcess 声明(kernel32.dll)
参数:lpApplicationName、lpCommandLine、lpProcessAttributes、lpThreadAttributes、bInheritHandles、dwCreationFlags、lpEnvironment、lpCurrentDirectory、lpStartupInfo、lpProcessInformation。 - PROCESS_INFORMATION 结构:hProcess、hThread、dwProcessId、dwThreadId。
- WaitForSingleObject:INFINITE 或自定义超时;返回值 WAIT_OBJECT_0、WAIT_TIMEOUT、WAIT_FAILED。
- CloseHandle 释放 hProcess、hThread,防止句柄泄漏。
- GetExitCodeProcess 获取退出码,验证外部程序执行结果。
- VB.NET 场景:System.Diagnostics.Process 的 StartInfo、WaitForExit、HasExited、ExitCode,以及“到底层句柄”的 Process.Handle。
- 常见坑:
- 路径带空格未加双引号;
- 当前目录未设置导致 DLL 加载失败;
- STA 线程阻塞 UI,需用 Async/Await(VB.NET)或后台线程(VB6)。
答案
(给出 VB6 与 VB.NET 两套完整工业级代码,可直接写白板)
VB6 版本
'模块级声明
Private Type STARTUPINFO
cb As Long
lpReserved As String
lpDesktop As String
lpTitle As String
dwX As Long
dwY As Long
dwXSize As Long
dwYSize As Long
dwXCountChars As Long
dwYCountChars As Long
dwFillAttribute As Long
dwFlags As Long
wShowWindow As Integer
cbReserved2 As Integer
lpReserved2 As Long
hStdInput As Long
hStdOutput As Long
hStdError As Long
End Type
Private Type PROCESS_INFORMATION
hProcess As Long
hThread As Long
dwProcessId As Long
dwThreadId As Long
End Type
Private Declare Function CreateProcess Lib "kernel32" Alias "CreateProcessA" _
ByVal lpApplicationName As String, _
ByVal lpCommandLine As String, _
ByVal lpProcessAttributes As Long, _
ByVal lpThreadAttributes As Long, _
ByVal bInheritHandles As Long, _
ByVal dwCreationFlags As Long, _
ByVal lpEnvironment As Long, _
ByVal lpCurrentDirectory As String, _
lpStartupInfo As STARTUPINFO, _
lpProcessInformation As PROCESS_INFORMATION) As Long
Private Declare Function WaitForSingleObject Lib "kernel32" _
ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" _
ByVal hObject As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" _
ByVal hProcess As Long, lpExitCode As Long) As Long
Private Const INFINITE As Long = &HFFFFFFFF
Private Const WAIT_OBJECT_0 As Long = 0
Public Function RunAndWait(ByVal exePath As String, ByVal params As String, Optional ByVal timeOutMs As Long = INFINITE) As Long
Dim si As STARTUPINFO, pi As PROCESS_INFORMATION
Dim cmd As String, ret As Long, exitCode As Long
si.cb = Len(si)
cmd = """" & exePath & """" & " " & params
If CreateProcess(vbNullString, cmd, 0, 0, 0, 0, 0, vbNullString, si, pi) = 0 Then
Err.Raise 5, , "CreateProcess failed, err=" & Err.LastDllError
End If
ret = WaitForSingleObject(pi.hProcess, timeOutMs)
If ret = WAIT_OBJECT_0 Then
GetExitCodeProcess pi.hProcess, exitCode
RunAndWait = exitCode
Else
RunAndWait = -1 '超时或异常
End If
CloseHandle pi.hThread
CloseHandle pi.hProcess
End Function
调用示例:
Dim rc As Long
rc = RunAndWait("C:\Program Files\MyApp\Tool.exe", "-batch", 30000)
If rc <> 0 Then MsgBox "外部程序异常退出,代码 " & rc
VB.NET 版本(展示“既用封装又拿句柄”)
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Module Runner
<DllImport("kernel32.dll", SetLastError:=True)>
Private Function WaitForSingleObject(hHandle As IntPtr, dwMilliseconds As UInteger) As UInt32
End Function
<DllImport("kernel32.dll", SetLastError:=True)>
Private Function CloseHandle(hObject As IntPtr) As Boolean
End Function
Public Function RunAndWaitNet(exePath As String, args As String, timeoutMs As Integer) As Integer
Using p As New Process
p.StartInfo.FileName = exePath
p.StartInfo.Arguments = args
p.StartInfo.UseShellExecute = False
If Not p.Start() Then
Throw New InvalidOperationException("启动失败")
End If
'方案 A:托管等待(推荐 99% 场景)
If Not p.WaitForExit(timeoutMs) Then
p.Kill()
Return -1 '超时
End If
Return p.ExitCode
'方案 B:若面试官追问“拿到底层句柄”
'Dim h As IntPtr = p.Handle
'Dim waitRet As UInt32 = WaitForSingleObject(h, CUInt(timeoutMs))
'If waitRet = &H0 Then
' Return p.ExitCode
'Else
' p.Kill()
' Return -1
'End If
End Using
End Function
End Module
面试时先写方案 A,再补充“如果非要原生句柄,可再拿 Process.Handle 去 WaitForSingleObject”,体现深度。
拓展思考
- 若外部程序可能再派生子进程,WaitForSingleObject 只能等待直接子进程,如何“等待孙子”?
→ 需用 Job Object(VB6 用 CreateJobObject + AssignProcessToJobObject,VB.NET 用 ManagedWinapi 库或 P/Invoke),把子进程加入作业,一旦作业句柄有信号即全部结束。 - 隐藏控制台窗口:VB6 在 STARTUPINFO 的 dwFlags 加入 STARTF_USESHOWWINDOW 且 wShowWindow = SW_HIDE;VB.NET 设置 StartInfo.WindowStyle = ProcessWindowStyle.Hidden。
- 实时读取输出:重定向标准输出,用异步读取事件,防止缓冲死锁;面试可提“我以前做打包工具时用管道实时回显日志”。
- UAC 与权限:若外部程序需要管理员,VB6 只能 ShellExecuteEx + runas;VB.NET 可在清单里加 requireAdministrator,或用 Verb = "runas"。
- 跨平台替代:.NET Core 以后有 Process.WaitForExitAsync,配合 CancellationToken 实现超时取消,展示你对新技术的跟进。