Batch files can not supress “terminate job”

后端 未结 2 753
后悔当初
后悔当初 2021-01-01 07:22

Im trying to open a 2nd batch file and detect if it normally exited or closed by a user (ctrl+c or x or window termiate etc..) so Im using this following example by Batch ru

相关标签:
2条回答
  • 2021-01-01 07:24
    1. Do not assign values to a volatile environment variable like errorlevel using set command. Doing that causes it becomes unvolatile in current context.
    2. Always use title in START "title" [/D path] [options] "command" [parameters].
    3. start "" /W cmd /c "anycommand&exit /B 12345" always returns 12345 exit code. It's because all the cmd line with & concatenated commands is prepared in parsing time (the same as a command block enclosed in parentheses) and then run entirely, indivisibly. Omit &exit /B 12345 to get proper exit code from anycommand, or replace it with something like start "" /W cmd /c "anycommand&&exit /B 12345||exit /B 54321" to get only success/failure indication.

    Next code snippet could help:

    @ECHO OFF
    SETLOCAL enableextensions
    
    set "_command=2nd_batch_file.bat"
    :: for debugging purposes
    set "_command=TIMEOUT /T 10 /NOBREAK"
    
    :: raise errorlevel 9009 as a valid file name can't contain a vertical line 
    invalid^|command>nul 2>&1
    
    echo before %errorlevel%
    start "" /w %comspec% /C "mode 70,10&title Folder Confirmation Box&color 1e&echo(&echo( Else the close window&%_command%" 
    echo after  %errorlevel%
    

    Output shows sample %_command% exit codes: 0 or 1 if came to an end properly but -1073741510 if terminated forceably by Ctrl+C or Ctrl+Break or red ×

    ==>D:\bat\SO\31866091.bat<nul
    before 9009
    after  0
    
    ==>D:\bat\SO\31866091.bat<nul
    before 9009
    after  1
    
    ==>D:\bat\SO\31866091.bat<nul
    before 9009
    ^CTerminate batch job (Y/N)?
    after  -1073741510
    
    ==>
    
    0 讨论(0)
  • 2021-01-01 07:35

    This works for me:

    call :runme start /w "Child Process" %comspec% /c "child.bat & exit 12345" <NUL >NUL 2>NUL 
    echo %ERRORLEVEL%
    goto :eof
    
    :runme
    %*
    goto :eof
    

    The idea is to call a subroutine in the current script rather than calling out to an external script. You can still redirect input and output for a subroutine call.

    0 讨论(0)
提交回复
热议问题