怎样判断CMD是否运行完毕,然后kill掉这个进程?
假设我这里shell一个cmd,并且发出了指令,用sleep的话我不能确定运行具体时间。
Shell("cmd.exe /c adb shell ls data/app > C:\applist.txt", AppWinStyle.Hide)比如这条指令,我要判断是否完成,然后shell一个taskkill把adb.exe关闭,怎么写? 判断结束 shell cmd
[解决办法]
http://msdn.microsoft.com/zh-cn/library/system.diagnostics.process.waitforexit.aspx
使用线程来调用 Process.Start,然后阻塞线程直到进程退出。
[解决办法]
有一种很VB的做法(在VB.NET里面要稍微修改下API定义),你可以了解到底层实现的机制,就是WaitForSingleObject。
Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32.dll" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function OpenProcess Lib "kernel32.dll" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId As Long) As Long
Private Const INFINITE = &HFFFF
Private Sub ShellAndWait(ByVal program_name As String)
Dim process_id As Long
Dim process_handle As Long
' Start the program.
On Error GoTo ShellError
process_id = Shell(program_name)
On Error GoTo 0
' Wait for the program to finish.
' Get the process handle.
process_handle = OpenProcess(SYNCHRONIZE, 0, process_id)
If process_handle <> 0 Then
WaitForSingleObject process_handle, INFINITE
CloseHandle process_handle
End If
Exit Sub
ShellError:
MsgBox "Error starting task " & _
txtProgram.Text & vbCrLf & _
Err.Description, vbOKOnly Or vbExclamation, _
"Error"
End Sub