Windows cmd program exit code

exit exit

Область применения: Windows Server (половина ежегодного канала), Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012 Applies to: Windows Server (Semi-Annual Channel), Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012

Выход из интерпретатора команд или текущего пакетного скрипта. Exits the command interpreter or the current batch script.

Синтаксис Syntax

Параметры Parameters

Параметр Parameter Описание Description
/b /b Выход из текущего пакетного скрипта вместо выхода из Cmd.exe. Exits the current batch script instead of exiting Cmd.exe. Если выполняется из-за пределов пакетного скрипта, выполняет выход из Cmd.exe. If executed from outside a batch script, exits Cmd.exe.
Указывает числовое число. Specifies a numeric number. Если указан параметр /b , переменной среды ERRORLEVEL присваивается это число. If /b is specified, the ERRORLEVEL environment variable is set to that number. Если интерпретатор команд закрывается, код завершения процесса устанавливается в это число. If you are quitting the command interpreter, the process exit code is set to that number.
/? /? Отображение справки в командной строке. Displays help at the command prompt.

Примеры Examples

Чтобы закрыть интерпретатор команд, введите: To close the command interpreter, type:

Getting the exit code of an application started with the “cmd” and “start” commands

I have a console application. Interaction with this application is done via TCP/IP.

I also have a test framework for it, which is basically a collection of BATCH scripts (. not my fault). What this test framework does for each test is basically this:

  1. start /min «myapplication.exe» and wait until verification is received that the application is up and running.
  2. send commands via TCP/IP to this application, receive its replies, and check if the timings and values agree with whatever is expected by the specific test.

One problem that I’m currently encountering is that the application exits prematurely due to some internal error. I would like to distinguish between failed tests, and the application crashing. The one and only indication I have for this, is the application’s exit code.

So, I tried the following:

start /min cmd /c «myapplication.exe || echo %errorLevel% > exitcode.txt»

and then later on in the test scripts,

but for some strange reason, the text file never appears, even though I sometimes get a dialog about the application crashing, and even though I forcibly make it fail with a known non-zero exit code. The test just goes through do_processing and (of course) results in failure.

EDIT When I run

start /min cmd /c «nonsense || echo %errorLevel% > test.txt»

I sometimes get a text file containing the string 9009, but other times that text file contains the string 0 , or sometimes 1 , . What the.

EDIT2 If you type

cmd /k «nonsense || echo %errorLevel%»

(note the /k option), you see 0 being printed in the new window, but if you then type echo %errorlevel% , you get 1 .

I knew batch was not very sane, but it should at least be consistently insane.

Any ideas on what could be going on here?

3 Answers 3

Normal expansion like %errorLevel% occurs when the statement is parsed, and the entire CMD /C command line is parsed in one pass, so the value you get is the value that existed before the commands were run (always 0).

You can get a more precise explanation at https://stackoverflow.com/a/4095133/1012053. It can be difficult to follow and understand the significance of the phases at first, but it is worth the effort.

To solve your problem you must delay expansion of the variable until after your exe has run.

You have two options:

Option 1) Use CALL to get a delayed round of expansion.

In a batch file you would double the percents. But the commands run using CMD /C are run under a command line context, not batch. Doubling the percents does not work under the command line.

Instead, you must introduce a caret (cmd.exe escape character) into the variable name. The first phase of expansion occurs before escapes are processed, so it looks for a name with the caret, and doesn’t find it. When not found, the command line parser preserves the original text when the variable is not found. Next the special characters are handled and the escape is consumed. So when the CALL round of expansion occurs, it sees the correct variable name.

I believe you are issuing the START command within a batch script, so you must also double the percents to prevent the parent batch script from expanding ERRORLEVEL.

Option 2) Use delayed expansion

Delayed expansion syntax is !errorlevel! instead of %errorlevel% . But before you can use it, delayed expansion must be enabled. In a batch script you would use setlocal enableDelayedExpansion , but that doesn’t work in a command line context. Instead, you must use the cmd.exe /v:on option.

Assuming your batch script has not enabled delayed expansion, then you would simply use the following:

But if your batch script has enabled delayed expansion, then you must escape the ! so that the parent batch script does not expand ERRORLEVEL. Note that you must still use /v:on because the STARTed sub-process (normally) defaults to disabled delayed expansion.

Windows batch script launch program and exit console

I have a batch script that I use to launch a program, such as notepad.exe . When I double click on this batch file, notepad starts normally, but the black window of the cmd who launched notepad.exe remains in the background. What do I have to do in order to launch notepad.exe and make the cmd window disappear?

edit: is more complicated than using \I .

The cmd calls cygwin , and cygwin starts notepad . I use

start \I \path\cygwin\bin\bash.exe

and the first window (cmd) disappears, but a second window (\cygwin\bin\bash.exe) is still on the background. In the cygwin script I used notepad.exe & and then exit.

6 Answers 6

Keep the «» in between start and your application path.

Added explanation:

Normally when we launch a program from a batch file like below, we’ll have the black windows at the background like OP said.

This was cause by Notepad running in same command prompt (process). The command prompt will close AFTER notepad is closed. To avoid that, we can use the start command to start a separate process like this.

This command is fine as long it doesn’t has space in the path. To handle space in the path for just in case, we added the » quotes like this.

However running this command would just start another blank command prompt. Why? If you lookup to the start /? , the start command will recognize the argument between the » as the title of the new command prompt it is going to launch. So, to solve that, we have the command like this:

How to get exit code after running command in cmd in windows c++

I am using Createprocess to run command in cmd and I am trying to get exit code of that specific command execution using GetExitCodeProcess() .

If command window is open and I try GetExitCodeProcess() then I get 259(STILL_ACTIVE) return code always. If I try to terminate the process using TerminateProcess() then I get exit code the value I sent to terminate the process.

Below is my code:

I should get nonzero error code when I pass /k dir as command and zero error code if I pass /k dirancbdf (any nonexistent command).

Another reason to use Terminateprocess is I want to hide/Show Command prompt based on success/failure of that command.

1 Answer 1

You are passing option /k to cmd.exe , meaning you want the shell to remain active after executing command dir . Doing this way, the process running the command will never ends and you will always get STILL_ACTIVE when querying GetExitCodeProcess() (meaning the process is still running).

If you want the exit code of the dir command, you should use option /c instead (so that cmd.exe ends after executig command dir ). Moreother, you should wait for the process to end using WaitForSingleObject() before querying GetExitCodeProcess() , because CreateProcess() will return immediately after creation of the process (it does not wait for the process to end). No need to call TerminateProcess() in this case : the dir command return status wil be available from GetExitCodeProcess() .

If you want the console to remain open if an error occur, you can use the following syntax :

where || ensures that the pause command is executed only if dir command fails, and && ensures that a an exit code of 1 is ouput in case of such an error.

How do I get the application exit code from a Windows command line?

I am running a program and want to see what its return code is (since it returns different codes based on different errors).

I know in Bash I can do this by running

What do I do when using cmd.exe on Windows?

7 Answers 7

A pseudo environment variable named errorlevel stores the exit code:

Also, the if command has a special syntax:

See if /? for details.

Example

Warning: If you set an environment variable name errorlevel , %errorlevel% will return that value and not the exit code. Use ( set errorlevel= ) to clear the environment variable, allowing access to the true value of errorlevel via the %errorlevel% environment variable.

Testing ErrorLevel works for console applications, but as hinted at by dmihailescu, this won’t work if you’re trying to run a windowed application (e.g. Win32-based) from a command prompt. A windowed application will run in the background, and control will return immediately to the command prompt (most likely with an ErrorLevel of zero to indicate that the process was created successfully). When a windowed application eventually exits, its exit status is lost.

Instead of using the console-based C++ launcher mentioned elsewhere, though, a simpler alternative is to start a windowed application using the command prompt’s START /WAIT command. This will start the windowed application, wait for it to exit, and then return control to the command prompt with the exit status of the process set in ErrorLevel .

Читайте также:  Не ставятся драйверы для linux
Оцените статью