- Как принудительно завершить процесс зависшей службы в Windows?
- Завершение зависшей службы с помощью TaskKill
- Принудительное завершение зависшей службы из PowerShell
- Анализ зависших процессов с помощью Resmon
- Process Explorer: Завершение зависшего процесса из-под SYSTEM
- Start or Stop the Web Server (IIS 8)
- To start or stop a web server
- Using the UI
- Using a command line
- Windows server 2012 service stopping
- Windows server 2012 service stopping
- Answered by:
- Question
- Answers
- All replies
Как принудительно завершить процесс зависшей службы в Windows?
Как завершить процесс службы Windows, зависшей в статусе stopping (остановка)? Думаю, большинство администраторов Windows, встречалось с ситуациями, когда при попытке остановить (перезапустить) службу из графического интерфейса консоли управления службами (Services.msc), служба зависает намертво и висит в статусе Stopping. После этого вы не можете остановить службу в консоли, т.к. кнопки действий службы становятся недоступными. Самый простой способ – перезагрузить сервер, но это не всегда допустимо. Рассмотрим альтернативный способ, позволяющий принудительно завершить зависшую службу или процесс без необходимости перезагрузки.
Если в течении 30 секунд после попытки остановки службы, она не останавливается, Windows выводит сообщение:
При попытке остановить такую службу командой: net stop wuauserv, появляется сообщение:
The service is starting or stopping. Please try again letter.
Завершение зависшей службы с помощью TaskKill
Наиболее простой способ завершить зависшую служу – воспользоваться утилитой taskkill. В первую очередь нужно определить PID (идентификатор процесса) нашей службы. В качестве примера возьмем службу Windows Update, ее системное имя wuauserv (имя можно посмотреть в свойствах службы в консоли services.msc).
В командной строке с правами администратора (это важно, иначе будет ошибка access denied):
sc queryex wuauserv
В данном случае PID процесса — 816.
Чтобы принудительно завершить зависший процесс с PID 816:
taskkill /PID 816 /F
SUCCESS: The process with PID 816 has been terminated.
Данная команда принудительно завершит процесс службы. В дельнейшем можно вернуться в консоль управления службами и вручную стартовать службу (или совсем удалить эту службу, если она не нужна).
«Выстрел в голову» зависшей службы можно выполнить и более элегантно, не выполняя ручное определение PID процесса. У утилиты taskkill есть параметр /FI, позволяющий использовать фильтр для выбора необходимых служб или процессов. Вы можете остановить конкретную службу командой:
TASKKILL /F /FI “SERVICES eq wuauserv”
Или можно вообще не указывать имя, службы, завершив все сервисы в зависшем состоянии с помощью команды:
taskkill /F /FI “status eq not responding”
После этого служба, зависшая в статусе Stopping должна остановиться.
Принудительное завершение зависшей службы из PowerShell
Также вы можете использовать PowerShell для принудительной остановки службы. С помощью следующей команды можно получить список служб, находящихся в состоянии Stopping:
Get-WmiObject -Class win32_service | Where-Object
Завершить процесс для всех найденных служб поможет командлет Stop-Process. Объединив обе операции в цикл, получим скрипт, автоматически завершающий все процессы подвисших служб в системе:
$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»
>
Анализ зависших процессов с помощью Resmon
Вы можете определить процесс, из-за которого зависла служба с помощью монитора ресурсов resmon.
- В окне Монитора ресурсов перейдите на вкладку ЦП (CPU) и найдите процесс зависшей службы;
- Выберите пункт Анализ цепочки ожидания (AnalyzeWaitChain);
- В новом окне скорее всего вы увидите, что вам процесс ожидает другой процесс. Завершите его. Если выполняется ожидание системного процесса 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;
- В разрешения службы предоставьте права FullControl для группы администраторов (Administrators). Сохраните изменения;
- Теперь попробуйте завершить процесс службы.
Start or Stop the Web Server (IIS 8)
Applies To: Windows Server 2012 R2, Windows Server 2012
You can stop IIS when you want to stop the web server from serving content, such as when you upgrade applications. To stop the web server, you must stop the Windows Process Activation Service (WAS) and the World Wide Web Publishing Service (W3SVC). You can then start the web server when you are ready for the web server to serve content again.
When you stop WAS and W3SVC, all sessions connected to your web server are dropped. Any in-memory session state is lost. All sites are unavailable until these services are restarted. Therefore, avoid stopping and restarting your web server if you can.
You must be a server administrator to perform this procedure.
To start or stop a web server
You can perform this procedure by using the user interface (UI) or a command line. For information about opening IIS Manager, see Open IIS Manager (IIS 8).
Using the UI
Open IIS Manager and navigate to the web server node in the tree.
In the Actions pane, click Start if you want to start the web server, Stop if you want to stop the web server, or Restart if you want to first stop IIS, and then start it again.
Using a command line
Open an elevated command-line window.
At the command prompt, type net stop WAS and press ENTER; type Y and then press ENTER to stop W3SVC as well.
To start the web server, type net start W3SVC and press ENTER to start both WAS and W3SVC.
If you want to stop IIS first, and then start it again, type iisreset /restart and press ENTER.
Windows server 2012 service stopping
Всем доброго времени суток.
Пару дней назад возникла непонятна ситуация с двумя серверами на Windows server 2012 r2, проблема заключается в следующем:
Есть два сервера:
Server1 — AD, DNS, DHCP, SQL, общая папка
Server2 — RemouteApp, 1C-сервер (SQL работает на третьем сервере)
Файловый антивирус Dr.web.
1) В подключенной rdp сессии на Server1 перестают открываться приложения, ранее запущенные приложения работают но постепенно начинают отваливаться, причем окно программы становится серым с обозначением «не отвечает».
Если закрыть rdp сессию, то повторно подключиться не получится процесс застопорится на «Подготовка удаленного компьютера»
2) При локальном входе на сервер Server1 процесс подключения зависает на «Работает клиент групповой политики» и дальше не двигается
3) При всем при этом службы AD, DNS, DHCP и общая папка продолжают функционировать (доменных пользователей на компы пускает, интернет работает, адреса раздаются, на общую папку файлы записываются и считываются).
4) В журнале Windows ошибок нет.
Все эти проблемы можно было бы списать на железо но вчера такие же симптомы вылезли на Server2 + через некоторое время отваливается RemouteApp.
В логах Server2 появились две группы сообщений в следующей последовательности:
1) Превышение времени ожидания (30000 мс) при ожидании ответа транзакции от службы «iphlpsvc».
2) Превышение времени ожидания (30000 мс) при ожидании ответа транзакции от службы «Appinfo».
3) Превышение времени ожидания (30000 мс) при ожидании ответа транзакции от службы «NlaSvc».
4) Служба «Служба регистрации ошибок Windows» перешла в состояние Остановлена.
5) Превышение времени ожидания (30000 мс) при ожидании ответа транзакции от службы «Schedule».
6) Запись кэша входа в систему для пользователя user1@MYDOMEN.LOCAL оказалась самой старой и была удалена. Отметка времени записи: 11/12/2015 10:02:31.
7) Превышение времени ожидания (30000 мс) при ожидании ответа транзакции от службы «iphlpsvc».
8) Превышение времени ожидания (30000 мс) при ожидании ответа транзакции от службы «NlaSvc».
9) Превышение времени ожидания (30000 мс) при ожидании ответа транзакции от службы «ShellHWDetection».
1) Запись кэша входа в систему для пользователя user2@MYDOMEN.LOCAL оказалась самой старой и была удалена. Отметка времени записи: 11/12/2015 9:53:02.
2) Превышение времени ожидания (30000 мс) при ожидании ответа транзакции от службы «iphlpsvc».
3) Служба «Служба регистрации ошибок Windows» перешла в состояние Остановлена.
4) Превышение времени ожидания (30000 мс) при ожидании ответа транзакции от службы «NlaSvc».
5) Превышение времени ожидания (30000 мс) при ожидании ответа транзакции от службы «ShellHWDetection».
6) Превышение времени ожидания (30000 мс) при ожидании ответа транзакции от службы «Schedule».
7) Служба «Диспетчер настройки устройств» перешла в состояние Работает.
других ошибок в журнале нет.
Подскажите в чем может быть проблема и куда капать? Или чем можно про диагностировать сервер чтоб определить проблему?
Windows server 2012 service stopping
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
The log shows the following events almost exactly every 5 minutes on a WS 2008 R2:
- The Software Protection service has stopped.
- The Software Protection service is starting.
- Initialization status for service objects.
- The Software Protection service has completed licensing status check.
- The Software Protection service has started.
These five events are within 2 seconds.
Could anyone shed some light on what is going on?
Thanks in advance.
Answers
You couldn’t really describe it as a bug since the SPP service is only doing what it should, which is logging requests that are being made to it.
The real task you have is to identify what the calling task is and then determine if there’s a reason it’s checking the licencing status so often and potentially lessening those checks. Going back to the previous post as an example, if it’s Server Manager, then you can actually configure the refresh interval or turn it off entirely (you’d have to tell the people running it to do this as there’s no central way of doing so as far as I know).
One thing you can do purely as a testing mechanic is to disable the firewall rules for «Windows Remote Management» (there’s two of them: port 5985 and port 80).
If you do this, then keep an eye on the event log and see if that stops the licensing events from generating. Just don’t forget to re-enable the firewall rule once you’re done.
All replies
It shouldn’t be running every five minutes unless something is wrong with the licencing status or you have a monitoring/management tool checking the licencing status of the server, which will require the service to start.
You can double-check the frequency of the scheduled task that usually handles the starting of the service within the Scheduled Tasks MMC here:
Task Scheduler Library\Microsoft\Windows\SoftwareProtectionPlatform
If the value for «Last Run Time» isn’t correlating with the timestamps you’re seeing on the event log entries, then you’ve got a monitoring/management process tripping the service.
Thanks a lot for the elucidation.
The «Last Run Time» is «Never». The status is «Disabled».
It stopped this morning after it lasted for about 27 hours.
I’m not sure what to make of the service resheculding task being disabled, but it sounds like some part of the initial licensing routine hasn’t completed successfully.
Are you actually using KMS infrastructure, or are you simply MAK-activating your servers?
What is the output from running the following command on the server in question?
Okay, that probably explains why the scheduled task is disabled then, as there’s no recurrent checks once a MAK key has been initially activated. That still leaves your original problem, of course.
What are the actual event IDs that are being generated? (They should still be from the Security-SPP source)
I’ll have to go away with those event IDs and see how they bear relevance to MAK activations, as we only use a KMS infrastructure here, and I’d expect to see some differences in the generated events given the 12288 and 12289 that we get only relate to KMS (as far as I understand it).
It seems the reply I posted yesterday did not go through. At least, I am not seeing it.
Anyways, let me repost events with their ID’s:
- The Software Protection service has stopped. 903
- The Software Protection service is starting. 900
- Initialization status for service objects. 1066
- The Software Protection service has completed licensing status check. 1003
- The Software Protection service has started. 902
So, I’ve done a little reading but I don’t have anything definitive. What are I do have are two links and some speculation. First, the links:
For the first post, I took the easy path and run Server Manager locally thinking it’d use the same behaviour and trigger the events, but it didn’t. I made sure I had the Refresh option (down the bottom of Server Manager) enabled, but it made no difference.
Running it remotely did yield quite a different result. Not only does it generate the events, and does so according to the refresh interval, it handles the licence checks differently.
Whereas the «normal» on-host process seems to handle the licence checks in bulk, logging a single 1003 event as a result, Server Manager — when run remotely, actually handles each licence check «individually» (I don’t know the actual SPP API well enough to be detailed about it) which results in a 1003 event for each and every licence type check.
Anyhow, once I closed Server Manager on the remote host the events also stopped.
I wouldn’t class any of this as absolute proof of cause, but it at least fits into my expectation that it was something outside of the service’s normal operation from my original post, which also corresponds to the second article referenced above, so I’m happy enough to accept that.
Of course, this doesn’t mean it’s Server Manager in your case, but it does seem to point to something that is in fact talking to the Software Protection service on that machine.
Thanks a lot for the investigation.
After reading your post, I checked my server and found it is happening again with the same interval — 5 minutes. The server runs SQL server and websites. No application is open.
The server is managed remotely via RDP.
According to the first post, it seems to be fairly common. Should we take it as a bug of WS?
You couldn’t really describe it as a bug since the SPP service is only doing what it should, which is logging requests that are being made to it.
The real task you have is to identify what the calling task is and then determine if there’s a reason it’s checking the licencing status so often and potentially lessening those checks. Going back to the previous post as an example, if it’s Server Manager, then you can actually configure the refresh interval or turn it off entirely (you’d have to tell the people running it to do this as there’s no central way of doing so as far as I know).
One thing you can do purely as a testing mechanic is to disable the firewall rules for «Windows Remote Management» (there’s two of them: port 5985 and port 80).
If you do this, then keep an eye on the event log and see if that stops the licensing events from generating. Just don’t forget to re-enable the firewall rule once you’re done.
Thanks a lot, Lain.
I thought I would try your suggestions when it occurred again, but it has not happened since last time. I will report back should it takes place again.
I have nearly the same issue, but it is a bit worse.
My worker role, which processes thousands of credit card transactions each night, just doesn’t work sometimes because «The software protection service has stopped».
This makes the entire cloud service go down and is costing us TONS of money. I thought running in the cloud was supposed to prevent these types of things from happening. Typical MSFT. I’m going to port this service to another language and just move over to Amazon.
i Have a same problem. Not in server. My PC is windows 10 pro. It freezes every 5 minutes or lesser than that it comes back after a few seconds. when i checked event viewer, it shows SPP has been stopped
I have read all this thread. but i dint find a solution for a PC
The Software Protection service (SPP) is designed to verify activation of any app that is registered with it. This includes Office and many Windows services. I would guess that services like Exchange, SQL, and most others are also a part of this.
Every time a registered app starts, it will send a request to SPP to verify the activation. If your copy of Windows is not activated, SPP will not start. If SPP does not start for any reason, SPP registered apps will fail to verify activation and they will not be permitted to run. After 30 seconds of inactivity, SPP will shut down.
The problem is that SPP can take a long time to start and will often time out, even though your system is properly registered. A second attempt will usually get it started, but I don’t want to retry 2 and 3 times just to open a Word doc. Server apps will not automatically retry once they fail the activation check.
My workaround is to increase the InactivityShutdownDelay for the SPP. The setting is located at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SoftwareProtectionPlatform. I set the InactivityShutdownDelay to 0x00015180(86400). Once it starts, the SPP will run for 24 hours without shutting down. This should be enough for a workstation. For server apps, try this and check your logs. If needed, you can try a longer timeout.
I do agree with Lain from an earlier posting . even with this, you should check the logs and make sure what apps are calling for the service.