- Команда EXIT: выход из командной строки Windows или командного файла
- Close programs from the command line (Windows)
- 5 Answers 5
- Update to Updated Question
- Windows command line exit status
- Errorlevel
- Ctrl-C
- How to get exit code after running command in cmd in windows c++
- 1 Answer 1
- Close programs from the command line (Windows)
- 5 Answers 5
- Update to Updated Question
Команда EXIT: выход из командной строки Windows или командного файла
При работе с операционными системами Windows пользователям и системным администраторам довольно часто приходится использовать командную строку. Большинство из нас привыкло пользоваться графическим интерфейсом системы, а потому закрывает окно командной строки, используя мышь. Впрочем, закончив набирать команды, можно не отрывать рук от клавиатуры, и закрыть окно командной строки через EXIT.
У команды exit есть и второе предназначение — выход из текущего командного файла. Допустим, что в текущем окне командного интерпретатора у вас исполняется какой-то BAT-файл или CMD-файл. Если нужно выйти из него, не закрывая окно командной строки, это также можно сделать командой exit . Синтаксис и примеры ниже.
B — завершение текущего командного файла вместо завершения процесса CMD.EXE (закрытия окна командной строки). Если использовать вне пакетного файла-сценария, будет завершён процесс CMD.EXE;
exitCode — цифровой код, определяющий номер для ERRORLEVEL. Если произошло завершение работы CMD.EXE, то будет установлен код завершения процесса с данным номером.
Команда выше просто закроет окно командной строки.
Нередки ситуации, когда один командный файл вызывает другой командный файл. Предположим, что файл primer1.bat вызывает файл primer2.bat. Используя команду exit , мы вызовем закрытие файла primer2.bat, а также primer1.bat, после чего закроется и окно командной строки.
Чтобы этого не произошло, используем /b . Допустим, что файл primer1.bat вызывает primer2.bat и выводит на экран значение ERRORLEVEL, которое взято при выходе из primer2.bat:
Файл primer2.bat завершается командой exit с установкой значения ERRORLEVEL, равного 128:
Это приведёт к выводу следующего сообщения:
Как видите, польза команды exit не только в том, что она помогает закрывать окно командной строки без помощи мыши.
Close programs from the command line (Windows)
What is the proper way to close/exit programs from command line, similar to pressing the «X» close button in the corner of the window?
Im trying to close chrome under 3 different versions of windows: win7 ultimate, win7 home, winXP
Under Ultimate and XP: TSKILL chrome
Under Home: TASKKILL /IM chrome.exe
(It closes chrome, no cmd errors,
but chrome error restore when relaunch it)
TASKKILL /IM chrome.exe :
(It closes chrome, no chrome errors when relaunch it,
but errors in cmd: «impossible to terminate child processes(about 4-5), only by force with /F «)
Should I ignore cmd child errors if on relaunch chrome show me no errors?
5 Answers 5
The proper way to close/exit a program ultimately depends upon the software. However, generally the best practice is for Windows programs to close whenever they receive the WM_CLOSE message. Properly releasing memory and closing handles. There are other messages that can signal the close of the application, but it is up to the author of the software how each message is handled.
taskkill sends the WM_CLOSE message and it is then up to the application whether to properly close. You may also want to use the /T option to also signal child processes.
Only use the /F option if you want to force the termination of the process.
Other options would include sending the Alt+F4 keys, using PowerShell, or 3rd party applications.
Update to Updated Question
Ignore, the errors. Chrome generates many processes. The errors are caused when an process does not acknowledge the WM_CLOSE message that TASKKILL sends. Only processes with a message loop will be able to receive the message, therefore, the processes that do not have a message loop will generate that error. Most likely, these processes are the chrome extensions and plugins.
To hide the errors capture the output
Summary: TASKKILL is the proper way via command line to close applications per its WM_CLOSE implementation and the Microsoft KB that I linked.
It has «closeprocess» command which is designed to close processes gracefully. As per its document, it does not terminate apps but sends WM_CLOSE to all top-level windows of the target process.
If this doesn’t work, I bet your application has an unusual cleanup procedure. I would like to see what happens inside so please let me know what your target application is.
The answer to that question can be found here (Microsoft link).
You can send WM_CLOSE messages to any window you wish to close. Many windows handle WM_CLOSE to prompt the user to save documents.
A tool that does this correctly is @Kill . Look also SendMsg.
I do not know how to do this in batch, but you could use the vbscript for this. Simulating the Alt + F4 keys (equates to signal WM_CLOSE ).
Run and look at the behavior of this script below.
Here is the list key names for SendKeys.
When you run the script, the notepad is open, some words are written and then a signal to close the program is delivered, see picture below.
Additional Questions
Can I start a program minimized, or background with vbscript?
Yes. Use the following code:
For more information check the Run Method .
Can chrome go to some url in vbscript?
If chrome is the default, use:
Is there a way to bring focus to specific application (chrome.exe)?
I want to send alt+f4 ONLY to chrome, independently of i’m doing with other windows.
The following code works on Windows 8.
There are some command-line utilities that can send a suitable WM_SYSCOMMAND message (with SC_CLOSE as the command) to a program’s top-level window. I’m sure that at least one will be mentioned shortly. (Then someone will mention AutoIt. Then there’ll be an answer showing how to do it with PowerShell and CloseMainWindow() .)
The command-line utility that comes as a built-in command in JP Software’s TCC, a command interpreter and command script processor for Windows, is called TASKEND .
Alright, Not going to lie. I saw this on stackoverflow and thought it was a challenging question. Soooo I just spent the last 2 hours writing some code. And here it is.
After following the steps below, you can type «TaskClose notepad.exe» after hitting «Start» and it will auto save all undocumented notepad files into desktop. It will auto-close chrome.exe and save the restoration settings.
You can add and remove additional settings for other applications under the if conditions. For instance:
The vbs and batch files performs the following procedures:
- Collects the executable.
- Queries the executable application names off of the tasklist.
- Performs an «Alt+TAB(x)» procedure until it has verified the window is open.
- Then Executes the rolling commands whether it be «Alt+F4» or even in extreme cases
- Alt+F4
- Activate Save
- AutoIncrememnt Filename
- Exit application.
ReturnAppList.bat : install in «C:\windows\system32\»
TaskClose.bat : install in «C:\windows\system32\» AND «C:\Users\YourUserName\»
TaskClose.vbs : install in «C:\windows\system32\»
This was alot of fun to write and I’m more happy about finishing it than actually showing the answer. Have a great week!
Windows command line exit status
Close the current batch script, exit the current subroutine or close the CMD.EXE session, optionally setting an errorlevel.
To close an interactive command prompt, the keyboard shortcut ALT + F4 is an alternative to typing EXIT.
Errorlevel
EXIT /b has the option to set a specific errorlevel, EXIT /b 0 for sucess, EXIT /b 1 (or greater) for an error.
The exit code can be an integer of up to 10 digits in length (positive or negative).
EXIT without an ExitCode acts the same as goto:eof and will not alter the ERRORLEVEL
n.b. You should never attempt to directly write to the %ERRORLEVEL% variable, ( SET ERRORLEVEL n ) instead use EXIT /b n as a safe way to set the internal ERRORLEVEL pseudo variable to n .
Ctrl-C
An errorlevel of -1073741510 will be interpreted by CMD.exe as a Ctrl-C Key sequence to cancel the current operation, not the entire script which EXIT will do.
To use this in a batch file, launch a new CMD session and immediately exit it, passing this errorlevel. The script will then act as though Ctrl-C had been pressed. Source and examples on DosTips.com.
::Ctrl-C
cmd /c exit -1073741510
When EXIT /b used with FOR /L, the execution of the commands in the loop is stopped, but the loop itself continues until the end count is reached. This will cause slow performance if the loop is (pointlessly) counting up to a large number.
In the case of an infinite loop, this EXIT /b behaviour will cause the script to hang until manually terminated with Ctrl + C
Exiting nested FOR loops, EXIT /b can be used to exit a FOR loop that is nested within another FOR loop.
This will only work if the inner FOR loop is contained in a separate subroutine, so that EXIT /b (or goto:eof) will terminate the subroutine.
Exit if a required file is missing:
@Echo Off
If not exist MyimportantFile.txt Exit /b
Echo If we get this far the file was found
@Echo Off
Call :setError
Echo %errorlevel%
Goto :eof
:setError
Exit /B 5
Use EXIT /b to exit a nested FOR loop (so skipping the values X,Y and Z), but still continue back to the main outer loop:
EXIT is an internal command.
If Command Extensions are disabled, the EXIT command will still work but may output a spurious ‘cannot find the batch label‘ error.
“Making music is not about a place you go. It’s about a place you get out of. I’m underwater most of the time, and music is like a tube to the surface that I can breathe through. It’s my air hole up to the world. If I didn’t have the music I’d be under water, dead”
VERIFY — Provides an alternative method of raising an error level without exiting.
TSKILL — End a running process.
Powershell: Exit — Exit Powershell or break — Exit a program loop.
Equivalent bash command (Linux): break — Exit from a loop.
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.
Close programs from the command line (Windows)
What is the proper way to close/exit programs from command line, similar to pressing the «X» close button in the corner of the window?
Im trying to close chrome under 3 different versions of windows: win7 ultimate, win7 home, winXP
Under Ultimate and XP: TSKILL chrome
Under Home: TASKKILL /IM chrome.exe
(It closes chrome, no cmd errors,
but chrome error restore when relaunch it)
TASKKILL /IM chrome.exe :
(It closes chrome, no chrome errors when relaunch it,
but errors in cmd: «impossible to terminate child processes(about 4-5), only by force with /F «)
Should I ignore cmd child errors if on relaunch chrome show me no errors?
5 Answers 5
The proper way to close/exit a program ultimately depends upon the software. However, generally the best practice is for Windows programs to close whenever they receive the WM_CLOSE message. Properly releasing memory and closing handles. There are other messages that can signal the close of the application, but it is up to the author of the software how each message is handled.
taskkill sends the WM_CLOSE message and it is then up to the application whether to properly close. You may also want to use the /T option to also signal child processes.
Only use the /F option if you want to force the termination of the process.
Other options would include sending the Alt+F4 keys, using PowerShell, or 3rd party applications.
Update to Updated Question
Ignore, the errors. Chrome generates many processes. The errors are caused when an process does not acknowledge the WM_CLOSE message that TASKKILL sends. Only processes with a message loop will be able to receive the message, therefore, the processes that do not have a message loop will generate that error. Most likely, these processes are the chrome extensions and plugins.
To hide the errors capture the output
Summary: TASKKILL is the proper way via command line to close applications per its WM_CLOSE implementation and the Microsoft KB that I linked.
It has «closeprocess» command which is designed to close processes gracefully. As per its document, it does not terminate apps but sends WM_CLOSE to all top-level windows of the target process.
If this doesn’t work, I bet your application has an unusual cleanup procedure. I would like to see what happens inside so please let me know what your target application is.
The answer to that question can be found here (Microsoft link).
You can send WM_CLOSE messages to any window you wish to close. Many windows handle WM_CLOSE to prompt the user to save documents.
A tool that does this correctly is @Kill . Look also SendMsg.
I do not know how to do this in batch, but you could use the vbscript for this. Simulating the Alt + F4 keys (equates to signal WM_CLOSE ).
Run and look at the behavior of this script below.
Here is the list key names for SendKeys.
When you run the script, the notepad is open, some words are written and then a signal to close the program is delivered, see picture below.
Additional Questions
Can I start a program minimized, or background with vbscript?
Yes. Use the following code:
For more information check the Run Method .
Can chrome go to some url in vbscript?
If chrome is the default, use:
Is there a way to bring focus to specific application (chrome.exe)?
I want to send alt+f4 ONLY to chrome, independently of i’m doing with other windows.
The following code works on Windows 8.
There are some command-line utilities that can send a suitable WM_SYSCOMMAND message (with SC_CLOSE as the command) to a program’s top-level window. I’m sure that at least one will be mentioned shortly. (Then someone will mention AutoIt. Then there’ll be an answer showing how to do it with PowerShell and CloseMainWindow() .)
The command-line utility that comes as a built-in command in JP Software’s TCC, a command interpreter and command script processor for Windows, is called TASKEND .
Alright, Not going to lie. I saw this on stackoverflow and thought it was a challenging question. Soooo I just spent the last 2 hours writing some code. And here it is.
After following the steps below, you can type «TaskClose notepad.exe» after hitting «Start» and it will auto save all undocumented notepad files into desktop. It will auto-close chrome.exe and save the restoration settings.
You can add and remove additional settings for other applications under the if conditions. For instance:
The vbs and batch files performs the following procedures:
- Collects the executable.
- Queries the executable application names off of the tasklist.
- Performs an «Alt+TAB(x)» procedure until it has verified the window is open.
- Then Executes the rolling commands whether it be «Alt+F4» or even in extreme cases
- Alt+F4
- Activate Save
- AutoIncrememnt Filename
- Exit application.
ReturnAppList.bat : install in «C:\windows\system32\»
TaskClose.bat : install in «C:\windows\system32\» AND «C:\Users\YourUserName\»
TaskClose.vbs : install in «C:\windows\system32\»
This was alot of fun to write and I’m more happy about finishing it than actually showing the answer. Have a great week!