Sign in to follow this  
Followers 0
therks

Exit code + StdoutRead/StderrRead

4 posts in this topic

Is there any way to retrieve the exit code from a process while also being able to use StdoutRead/StderrRead?

Share this post


Link to post
Share on other sites



Have a look at this example that pulled from this and edited.

Example.au3

#include <Constants.au3>
#include "ProcessExitCode.au3"
 
$iPid = Run(@ComSpec & ' /c dir /g', @WindowsDir, @SW_SHOW, $STDERR_CHILD + $STDOUT_CHILD)
$hHandle = _ProcessGetHandle($iPid)
ShowStdOutErr($hHandle)
$iExitCode = _ProcessGetExitCode($iPid)
_ProcessCloseHandle($hHandle)
MsgBox(0, "Program returned with exit code:", $iExitCode)
 
$iPid = Run(@ComSpec & ' /c dir', @WindowsDir, @SW_SHOW, $STDERR_CHILD + $STDOUT_CHILD)
$hHandle = _ProcessGetHandle($iPid)
ShowStdOutErr($hHandle)
$iExitCode = _ProcessGetExitCode($hHandle)
_ProcessCloseHandle($hHandle)
MsgBox(0, "Program returned with exit code:", $iExitCode)
 
Func ShowStdOutErr($l_Handle, $ShowConsole = 1)
    Local $Line, $tot_out, $err1 = 0, $err2 = 0
    Do
        Sleep(10)
        $Line = StdoutRead($l_Handle)
        $err1 = @error
        $tot_out &= $Line
        If $ShowConsole Then ConsoleWrite($Line)
        $Line = StderrRead($l_Handle)
        $err2 = @error
        $tot_out &= $Line
        If $ShowConsole Then ConsoleWrite($Line)
    Until $err1 And $err2
    Return $tot_out
EndFunc   ;==>ShowStdOutErr

ProcessExitCode.au3

#include-once
; #FUNCTION# ====================================================================================================================
; Name...........: _ProcessGetHandle()
; Description ...: Returns a handle from use of Run().
; Syntax.........: _ProcessGetHandle($iPID)
; Parameters ....: $iPID - ProcessID returned from a Run() execution
; Return values .: On Success - Returns Process handle while Run() is executing (use above directly after Run() line with only PID parameter)
;                 On Failure - 0
; Author ........: MHz (Thanks to DaveF for posting these DllCalls in Support Forum)
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......:
; ===============================================================================================================================
Func _ProcessGetHandle($iPID) ;Return handle of given PID
    Local Const $PROCESS_QUERY_INFORMATION = 0x0400
    Local $avRET = DllCall("kernel32.dll", "ptr", "OpenProcess", "int", $PROCESS_QUERY_INFORMATION, "int", 0, "int", $iPID)
    If @error Then
        Return SetError(1, 0, 0)
    Else
        Return $avRET[0]
    EndIf
EndFunc   ;==>_ProcessGetHandle
 
; #FUNCTION# ====================================================================================================================
; Name...........: _ProcessCloseHandle()
; Description ...: Closes a handle from use of Run().
; Syntax.........: _ProcessCloseHandle($hProc)
; Parameters ....: $hProc - Process handle
; Return values .: On Success - Closes Process handle after a Run() has executed.;
;                 On Failure - 0
; Author ........: MHz (Thanks to DaveF for posting these DllCalls in Support Forum), PsaltyDS
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......:
; ===============================================================================================================================
Func _ProcessCloseHandle($hProc) ;Close process handle
    Local $avRET = DllCall("kernel32.dll", "int", "CloseHandle", "ptr", $hProc)
    If @error Then
        Return SetError(1, 0, 0)
    Else
        Return 1
    EndIf
EndFunc   ;==>_ProcessCloseHandle
 
; #FUNCTION# ====================================================================================================================
; Name...........: _ProcessGetExitCode()
; Description ...: Returns a handle/exitcode from use of Run().
; Syntax.........: _ProcessGetExitCode($hProc)
; Parameters ....: $hProc   - Process handle
; Return values .: On Success - Returns Process Exitcode when Process does not exist.
;                 On Failure - 0
; Author ........: MHz (Thanks to DaveF for posting these DllCalls in Support Forum), PsaltyDS
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......:
; ===============================================================================================================================
Func _ProcessGetExitCode($hProc) ;Get process exit code from handle
    Local $t_ExitCode = DllStructCreate("int")
    Local $avRET = DllCall("kernel32.dll", "int", "GetExitCodeProcess", "ptr", $hProc, "ptr", DllStructGetPtr($t_ExitCode))
    If @error Then
        Return SetError(1, 0, 0)
    Else
        Return DllStructGetData($t_ExitCode, 1)
    EndIf
EndFunc   ;==>_ProcessGetExitCode

Adam

Share this post


Link to post
Share on other sites

Thanks, that works perfectly. And I can use _WinAPI_OpenProcess() and _WinAPI_CloseHandle() from the WinAPI.au3 include. Sorry for the horrendous reply time, I don't get back here often.

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

This a simpler quick and dirty way

FileDelete("C:\temp\errorlevel.txt")

$file = fileopen(@TempDir & "\CMD.bat",2)
FileWrite($file,"start /wait c:\temp\test2.exe" & @CRLF)
FileWrite($file,"echo %errorlevel% > C:\temp\errorlevel.txt" & @CRLF)
FileClose($file)

$PID = run(@TempDir & "\CMD.bat")


While ProcessExists($PID)
wend

$file = fileopen("C:\temp\errorlevel.txt",0)
msgbox(0,"",fileread($file))
fileclose($file)
Edited by castens

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • Vivaed
      Running PS1 Script with Parameters
      By Vivaed
      Trying to automate the sideload of a Windows Store app via .ps1 script...
      RunWait(@ComSpec & ' /c' & 'C:\"WB Resources"\APP_Prod\Add-AppDevPackage.ps1') Above doesn't work... I assume this is trying to open in CMD.
       
      Normally we right click the .ps1 and open with powershell, then we have to type "A" to start the install, it installs and then type any yet to exit.
      However I cant get the powershell to even open.
      Kind of puzzled here, any suggestions would be a help.
      PS I also tried to convert the .ps1 to exe, but that was a huge failure... lol
    • Vivaed
      Run(@ComSpec...) with schtasks
      By Vivaed
      I have this button in an app I am building:
      When you click it, it then opens a FileOpenDialog() I select and XML, then it asks for a name input, enter the name, then it should run the following code:
      schtasks.exe /create /tn XXXX-task /XML C:\WBRESO~1\WB-LOO~1\TESTIN~1.XML It works when I put it in the CMD and run it, I get SUCCESS! and the new task has been created in Task Scheduler.
      C:\Users\vivaed>schtasks.exe /create /tn XXXX /xml C:\WBRESO~1\WB-LOO~1\TESTIN~1.XML SUCCESS: The scheduled task "XXXX" has successfully been created. But when I run it in:
      (This is just a snippet of the code, there is a lot more)
      #include <AutoItConstants.au3> Global $wbResources = 'C:\"WB Resources"\WB-LoopChecker\' Case $Button4 $getXML = FileOpenDialog("Find task to import", $wbResources ,"XML (*.xml)") If @error Then ; Display the error message. MsgBox($MB_SYSTEMMODAL, "", "No file was selected.") Else Local $taskName = InputBox("Name this task","File: " & @CRLF & $getXML & @CRLF & "Name this task:" & @CRLF,"XXXX-task") $schedTask = 'schtasks.exe /create /tn ' & $taskName & ' /XML ' & FileGetShortName($getXML) Run(@ComSpec & " /c " & $schedTask, @SW_HIDE) ConsoleWrite($wbResources & @CRLF) ConsoleWrite($schedTask & @CRLF) EndIf Here I dont get any errors but the when I refresh the Task Scheduler, there is no new task....
       
    • FMS
      Run command doen't work
      By FMS
      Hello,
      I've some troubles whit the run command.
      Below u see 2 command's , 1 is working and the other not. (the first isn't working)
      I think the problem is in te space between program and files.Also I've treid every thing i could think of or the helpfiles handed to me.
      (or maybe I din't find the correct answer:))
      I tried so mush that i don't know anymore if it's the space between program files or not.
      Could somebody point me in the right direction?
      Not working:
      Run(@ComSpec & " /c psexec -i \\127.0.0.1 -u username -p pass -h -d /accepteula C:\Program Files\some_prog\Shell.exe" ,"C:\tools", @SW_HIDE) Working :
      Run(@ComSpec & " /c psexec -i \\127.0.0.1 -u username -p pass /accepteula cmd" , "C:\tools" , @SW_HIDE)  
       
       
       
       
       
       
    • NiceBoy1234
      Check wether AutoitScript has finished
      By NiceBoy1234
      How can I check wether my current autoitscript (.exe) has finished,

      my problem is that I have a button which starts the autoit, if the user clicks twice in the button or more times the script shall check if its runs or not
    • NiceBoy1234
      Run Command in Shell Execute
      By NiceBoy1234
      How can I run this command:
       
           Send( 'C:\xampp\htdocs\myApp\BuildDVD.exe ..\..\projects\dvdrom\' & $sFileName & '\project.xml ..\..\projects\' & $sFileName & '\video')

      in a Shell Execute?

      I can run
      ShellExecute('C:\xampp\htdocs\myApp\BuildDVD.exe')

      but how to I add the rest of the command?