Как завершить процесс службы Windows, которая зависла в статусе stopping (остановка) или starting (запуск)? Большинство администраторов Windows встречалось с ситуациями, когда при попытке остановить (перезапустить) службу из графического интерфейса консоли управления службами (
Services.msc
), служба зависает намертво и висит в статусе Stopping (или Starting). При этом все кнопки управления службой в консоли (Start, Stop, Restart) становятся недоступными (серыми). Самый простой способ – перезагрузить сервер, но это не всегда допустимо. Рассмотрим альтернативные способы, позволяющие принудительно завершить зависшую службу или процесс без необходимости перезагрузки Windows.
Если в течении 30 секунд после попытки остановки службы, она не останавливается, Windows выводит сообщение:
Не удалось остановить службу xxxxxxx Windows на локальном компьютере. Ошибка 1053. Служба не ответила на запрос своевременно.
Windows Could not stop the xxxxxx service on Local Computer Error 1053: The service did not respond in a timely fashion.
При попытке остановить такую службу командой:
net stop wuauserv
, появляется сообщение:
The service is starting or stopping. Please try again later.
Или:
[SC] ControlService: ошибка: 1061: Служба в настоящее время не может принимать команды.
Windows could not stop the Service on Local Computer. Error 1061: The service cannot accept control messages at this time.
Содержание:
- Как остановить зависшую службу Windows из командной строки?
- Принудительное завершение зависшей службы в PowerShell
- Анализ цепочки ожидания зависшего приложения с помощью ResMon
- Process Explorer: Завершение зависшего процесса из-под SYSTEM
Как остановить зависшую службу Windows из командной строки?
Самый простой способ завершить зависшую служу – воспользоваться утилитой taskkill. В первую очередь нужно определить PID (идентификатор процесса) нашей службы. В качестве примера возьмем службу Windows Update. Ее системное имя wuauserv (имя можно посмотреть в свойствах службы в консоли
services.msc
).
Важно. Будьте внимательными. Принудительная отставка процесса критичной службы Windows может привести к BSOD или перезагрузке операционной системы.
Отройте командную строку с правами правами администратора (иначе будет ошибка access denied) и выполите команду:
sc queryex wuauserv
В данном случае PID процесса —
9186
.
Чтобы принудительно завершить зависший процесс с PID 9186 воспользуйтесь утилитой taskkill:
taskkill /PID 9168 /F
SUCCESS: The process with PID 9168 has been terminated.
Данная команда принудительно завершит процесс службы. Теперь вы можете запустите службу командой sc start servicename или через консоль управления службами (или совсем удалить эту службу, если она не нужна).
«Выстрел в голову» зависшей службы можно выполнить и более элегантно, не выполняя ручное определение PID процесса. У утилиты taskkill есть параметр /FI, позволяющий использовать фильтр для выбора необходимых служб или процессов. Вы можете остановить конкретную службу командой:
TASKKILL /F /FI “SERVICES eq wuauserv”
Или можно вообще не указывать имя, службы, завершив все сервисы в зависшем состоянии с помощью команды:
taskkill /F /FI “status eq not responding”
После этого служба, зависшая в статусе Stopping должна остановиться.
Также вы можете использовать утилиту taskkill для принудительной остановки зависших служб на удаленном компьютере:
TASKKILL /S CORPFS01 /F /FI “SERVICES eq wuauserv”
Принудительное завершение зависшей службы в PowerShell
Также вы можете использовать PowerShell для принудительной остановки службы. С помощью следующей команды можно получить список служб, находящихся в состоянии Stopping:
Get-WmiObject -Class win32_service | Where-Object {$_.state -eq 'stop pending'}
Завершить процесс для всех найденных служб поможет командлет Stop-Process. Следующий PowerShell скрипт завершит все процессы зависших служб в Windows:
$Services = Get-WmiObject -Class win32_service -Filter "state = 'stop pending'"
if ($Services) {
foreach ($service in $Services) {
try {
Stop-Process -Id $service.processid -Force -PassThru -ErrorAction Stop
}
catch {
Write-Warning -Message " Error. Error details: $_.Exception.Message"
}
}
}
else {
Write-Output "No services with 'Stopping'.status"
}
В новом PowerShell Core 6.x/7.x вместо командлета Get-WmiObject нужно использовать Get-CimInstance. Замените первую команду скрипта на:
$Services = Get-CimInstance -Class win32_service | where-Object state -eq 'stop pending'
Анализ цепочки ожидания зависшего приложения с помощью ResMon
Вы можете определить процесс, из-за которого зависла служба с помощью монитора ресурсов (
resmon.exe
).
- В окне Монитора ресурсов перейдите на вкладку ЦП (CPU) и найдите процесс зависшей службы;
- Выберите пункт Анализ цепочки ожидания (Analyze Wait Chain);
- В новом окне скорее всего вы увидите, что вам процесс ожидает другой процесс. Завершите его. Если выполняется ожидание системного процесса svchost.exe, завершать его не нужно. Попробуйте проанализировать цепочку ожидания для этого процесса. Найдите PID процесса, которого ожидает ваш svchost.exe и завершите его
Process Explorer: Завершение зависшего процесса из-под SYSTEM
Некоторые процессы, запущенные из-под SYSTEM, не может завершить даже локальный администратора сервера. Дело в том, что у него просто может не быть прав на некоторые процессы или службы. Чтобы завершить такие процесс (службы), вам необходимо предоставить локальной группе Administrators права на службу (процесс), а потом завершить их. Для этого нам понадобятся две утилиты: psexec.exe и ProcessExplorer (доступны на сайте Microsoft).
- Чтобы запустить утилиту ProcessExplorer с правами системы (SYSTEM), выполните команду:
PSExec -s -i ProcExp.exe
- В списке процессов Process Explorer найдите процесс зависшей службы и откройте ее свойства;
- Перейдите на вкладку Services, найдите свою службу и нажмите кнопку Permissions;
- В разрешения службы предоставьте права Full Control для группы администраторов (Administrators). Сохраните изменения;
- Теперь попробуйте завершить процесс службы.
Обратите внимание, что права на службу и ее процесс выдались временно, до ее перезапуска. Для предоставления постоянных прав на службы познакомьтесь со статьей Права на службы в Windows.
Таймаут, в течении которого Service Control Manager ждет ожидания запуска или остановки службы можно изменить через параметр реестра ServicesPipeTimeout. Если служба не запускается в течении указанного таймаута, Windows записывает ошибку в Event Log (Event ID: 7000, 7009, 7011, A timeout was reached 30000 milliseconds). Вы можете увеличить этот таймаут, например до 60 секунд:
reg add HKLM\SYSTEM\CurrentControlSet\Control /v ServicesPipeTimeout /t REG_SZ /d 600000 /f
Это бывает полезным при запуске/остановки тяжелых служб, которые не успевают завершить все процессы быстро (например, MS SQL Server).
The taskkill
command can be used many different ways to end or kill running processes on Windows Server 2012 and above. Taskkill
replaces the kill
command that is available in lower versions of Windows.
Processes can be killed by either Process ID (PID) or Image (Process) Name.
A full description of the options available and various examples can be found in the Microsoft Windows Documentation for taskkill.
The command below will end all running processes with the name notepad.exe:
taskkill /F /IM notepad.exe /T
- /F = force the process to terminate
- /IM = specify the image name
- /T = terminate the specified process and any child processes started by it
I hope that helps someone to be able to kill all processes with the same name on Windows.
Author
Stewart Schatz
Career: Principal CNC Consultant for Syntax Systems Limited specializing Oracle JD Edwards EnterpriseOne and the technology that supports it.
Side Hustle: Owner/Operator of E1Tips.com
Location: Lancaster, PA USA
What I like to do: Invest in Family, Explore Technology, Lead Teams, Share Knowledge/Experience, Hunt, Hike, etc.
We use the taskkill
command to terminate applications and processes in the Windows command prompt. Running taskkill
is the same as using the End task button in the Windows Task Manager.
With taskkill
, we kill one or more processes based on the process ID (PID) or name (image name). The syntax of this command is as follows:
taskkill /pid PID
taskkill /im name
You can use the tasklist command to find the PID or image name of a Windows process.
The /F
option tells Windows to force kill the process:
taskkill /f /im notepad.exe
Kill a Process by PID
In the following example, we run the taskkill
command to terminate a process with a PID of 1000:
taskkill /f /pid 3688
The multiple processes can be terminated at once, as shown in the following example:
taskkill /pid 3688 /pid 4248 /pid 4258
Kill a Process by Name
To kill a process by its name, we use the /IM
option. In the following example, we run the taskkill
command to terminate the notepad.exe
process:
taskkill /im notepad.exe
The /t
option tells Windows to terminate the specified process and all child processes. In the following example, we force kill Microsoft Edge and its child processes:
taskkill /f /t /im msedge.exe
Command Options
/S | Specifies the IP Address or name of the remote system to connect to. |
/U | Specifies the name of the Windows user under which the command should execute. |
/P | Password for the user. Prompts for input if omitted. |
/FI | This option is to apply filters (see examples below). |
/PID | Specifies the PID of the process to be terminated. |
/IM | Specifies the image name of the process to be terminated. |
/T | Terminates the specified process and its child processes (end all tasks). |
/F | Forcefully kill a process. |
Examples
Terminate a process with a PID of 4000:
taskkill /pid 4000
Terminate spoolsv.exe
(which is the Print Spooler service on Windows):
taskkill /im spoolsv.exe
Using /f
and /t
options to forcefully terminate the entire process tree of the Microsoft Edge browser:
taskkill /f /t /im msedge.exe
Force kill any process that starts with the name note:
taskkill /f /t /im note*
In the following example, we terminate all processes that are not responding by using a filter:
taskkill /f /fi "status eq not responding"
In the above example, eq
stands for equal. You can use the following filters with the /fi
option.
Run taskkill
command on a remote computer:
taskkill /s 192.168.1.100 /u robst /pid 5936
In the above example, the process with PID 5936 will be terminated on a remote computer with an IP address of 192.168.1.100
.
Note that the Windows Firewall must be configured on the remote computer to allow the taskkill
command. Click the link below for instructions on how to do it.
How to allow tasklist and taskkill commands from Windows Firewall
All right, here’s the end of this tutorial. While working on the CMD, you can run taskkill /?
to display the help page, command options, and filters of the tasklist
command.
The PowerShell equivalent to the taskkill
is the Stop-Process
cmdlet. But you can always use taskkill
in PowerShell as well.
We can kill a process from GUI using Task manager. If you want to do the same from command line., then taskkill is the command you are looking for. This command has got options to kill a task/process either by using the process id or by the image file name.
Kill a process using image name:
We can kill all the processes running a specific executable using the below command.
taskkill /IM executablename
Example:
Kill all processes running mspaint.exe:
c:\>taskkill /IM mspaint.exe SUCCESS: Sent termination signal to the process "mspaint.exe" with PID 1972.
Kill a process forcibly
In some cases, we need to forcibly kill applications. For example, if we try to to kill Internet explorer with multiple tabs open, tasklist command would ask the user for confirmation. We would need to add /F flag to kill IE without asking for any user confirmation.
taskkill /F /IM iexplore.exe
/F : to forcibly kill the process. If not used, in the above case it will prompt the user if the opened pages in tabs need to be saved.
To kill Windows explorer, the following command would work
C:\>taskkill /F /IM explorer.exe SUCCESS: The process "explorer.exe" with PID 2432 has been terminated.
The above command would make all GUI windows disappear. You can restart explorer by running ‘explorer’ from cmd.
C:\>explorer
Not using /F option, would send a terminate signal. In Windows 7, this throws up a shutdown dialog to the user.
C:\>taskkill /IM explorer.exe SUCCESS: Sent termination signal to the process "explorer.exe" with PID 2432. C:\>
Kill a process with process id:
We can use below command to kill a process using process id(pid).
taskkill /PID processId
Example:
Kill a process with pid 1234.
taskkill /PID 1234
Kill processes consuming high amount of memory
taskkill /FI "memusage gt value"
For example, to kill processes consuming more than 100 MB memory, we can run the below command
taskkill /FI "memusage gt 102400"
More examples
Sometimes applications get into hung state when they are overloaded or if the system is running with low available memory. When we can’t get the application to usable state, and closing the application does not work, what we usually tend to do is kill the task/process. This can be simply done using taskkill command.
To kill Chrome browser from CMD
Taskkill /F /IM Chrome.exe
Kill Chromedirver from command line
Taskkill /F /IM Chromedriver.exe
To kill firefox browser application
taskkill /F /IM firefox.exe
To kill MS Word application(Don’t do this if you haven’t saved your work)
taskkill /F /IM WinWord.exe
Sometimes, the command window itself might not be responding. You can open a new command window and kill all the command windows
taskkill /F /IM cmd.exe
This even kills the current command window from which you have triggered the command.
Download Article
Using the taskkill command to end Windows processes
Download Article
- Ending a Process
- Forcefully Ending a Process
- Ending all Non-Responsive Programs
- Tips
|
|
|
Taskkill is a Windows Command Prompt (cmd) command that ends one or more tasks. It’s kind of like ending a task with Task Manager, but from the command line.[1]
Taskkill can also do things like forcefully end a program if it won’t close normally, or it can terminate multiple programs at once. For most people, Task Manager is the best program to use, but knowing taskkill is useful if you are writing a program, or if you need to do something more advanced. This wikiHow article will teach you how to use the taskkill command to force quit programs on your Windows PC.
Running the Taskkill Command in Windows
Open the Command Prompt app and type in «tasklist.» Find the program you want to end. Type in «taskkill /IM [Image Name of the program]» and hit «Enter.» Type » /F» at the end of the command to forcefully end the process. To end all non-responsive programs, type «taskkill FI «STATUS eq NOT RESPONDING» /F.»
-
Click start
, type Command Prompt into the search bar, and then click on «Command Prompt»
in the results.
- To start Command Prompt as administrator, right-click it, and select «Run as administrator». You will need to do this to end any programs that are also running as administrator.
-
2
Type in tasklist. This will display all running processes on the computer.[2]
It’s important to run this command first so that you can find the process names of the ones that you want to terminate.Advertisement
-
3
Review the list. Review the task list to search for the program that you want to end. Look at the «Image Name» specifically, since you will need this information to kill the task.
- You will probably have to scroll down to review all of the processes since they won’t fit all on one page.
-
4
Kill the task. First, you need to type in taskkill. Then, you have to specify that you are killing the task based on its image name, so put in a space, and then type in /IM. After this, put in another space, and then type in the Image Name of the program that you want to end. For this example, notepad.exe will be the task that will be killed. Afterwards, press ↵ Enter. This will kill the task.
- For this example, the whole command would look like taskkill /IM notepad.exe.
Advertisement
-
1
Type in tasklist. Just like the previous task, you need to type in tasklist to view the running programs and to retrieve the image name.[3]
-
2
Type in the regular taskkill command. You would first type in the command like your normally would. For example, to forcefully kill notepad.exe, you would type in taskkill /IM notepad.exe.[4]
-
3
Add /F to the end of the command. The «/F» argument tells taskkill that you want to forcefully end the process. Keep in mind that you have to add a space before adding this argument.[5]
Advertisement
-
1
Type in taskkill. This is the beginning of the command.
-
2
Type /FI "STATUS eq NOT RESPONDING". This specifies that you want to kill all programs that are not responding. Remember that you need to add a space after taskkill.[6]
-
3
Add /F to the end. Since non-responsive programs will not close on their own, they need to be forcefully closed. Then, press ↵ Enter. This will end all non-responsive programs.[7]
- Remember to add the space before typing /F.
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
The taskkill command is not case sensitive
-
There are many other things that taskkill can do, but most people will not need to use them. You can view all arguments for the taskkill command here.
-
Be careful with the command prompt. Although taskkill cannot really harm your computer, other commands can cause damage. You can always see what a command does by typing the first part, and then typing in /? after it.
Thanks for submitting a tip for review!
Advertisement
References
About This Article
Thanks to all authors for creating a page that has been read 93,414 times.