Kill process in PowerShell - windows

I tried to kill process from PowerShell by Stop-Service -Name (service name).
Sometimes the process exits properly, but sometimes even though the service gets stopped the background Java process for this app doesn't stop. Is there a solution to stop Java if it hasn't from PowerShell. The problem is that we have to find the right Java process and kill only that as we have other Java processes also running.

Stop-Service doesn't kill a process. It makes a request to the service control manager (SCM) to ask it to stop a service with a particular name. The SCM will then call into the process hosting the service and ask it to stop.
It's possible that the service won't shut down correctly when asked, and the SCM will timeout the call to stop the service. This tends to lead to the service showing as stopped in the SCM but still running in the background, which is what you are seeing.
If you want to explicitly kill the process hosting the service then you'll need to find a way to map the service name to a process id. This question may help you.

Related

Windows service cannot be killed

I've got a service that needs to be resarted, but all attempts to kill it fail.
I have tried everything i've found online and nothing has seemed to work.
The core issue seems to be that Services is holding onto the process and not allowing it to be killed
ERROR: The process with PID 11204 (child process of PID 572) could not be terminated.
Reason: There is no running instance of the task.
this happens when i try to force kill the task using taskkill/f /pid 11204 /t
PID 572 is services, so i cannot kill it without crashing windows.
There is also an Interactive Services detection that is activating but just leads to a blank screen i can't exit out of (since the process is dead) but turning this off still doesn't allow me to kill it.
I've found similar issues around but none seem to have the problem of the program being a child of services, and so can't kill the parent.
Is a system restart the ONLY option here? This is a production server and so restarting has to be done only at scheduled downtime, so looking for other options.
Services should be controlled via services APIs, or SCcommand-line tool. Try SC stop command.
On a call to ControlService[Ex] with SERVICE_CONTROL_STOP, explicitly from your SW or from SC tool, service's Handler[Ex] should receive SERVICE_CONTROL_STOP. At this point service should
Stop all its own started threads and free its own allocated resources
If it takes long, should also call SetServiceStatus with SERVICE_STOP_PENDING before that
Call SetServiceStatus with SERVICE_STOPPED to inform the system that is is no longer running
Return from Handler[Ex]
If the service was the only service in its process, StartServiceCtrlDispatcher is likely to return shortly, and at this point service process should exit. If there are other services in the process, StartServiceCtrlDispatcher will not return, and process should not exit, but the service being stopped is considered stopped anyway.

In Windows 7, how to send a Ctrl-C or Ctrl-Break to a separate process

Our group has long running processes which run daily. The processes are typically started at 9pm on any given day and run until 7pm the next day. Thus they typically run 22hrs/day. They are started by scheduled tasks on servers under a particular generic user ID, and they start and run regardless of whether or not that user ID is logged on. Thus, they are windowless console executables.
The tasks orchestrate computations running on a large server farm. Generally these controlling tasks run uninterrupted for the full 22hrs/day. However, we often have a need to stop and restart these processes. Because they control a multitude of tasks running on our server farm, it is important that they be shut down cleanly, so that they can stop and shut down all the server farm processes. Which brings me to our problem.
The controlling process has been programmed to respond to ctrl-C and ctrl-break signals. This works fine when the process is manually started in a console where we have access to the console and can "type" ctrl-c or ctrl-break in the console window. However, as mentioned, the processes typically run as windowless scheduled tasks. Hence we cannot "type" anything into a non-existent console window. Because they are console processes that execute without a logon process, the also must be able to execute in a completely windowless environment. So, how do we set up the process to listen for a shut-down signal?
While the process does indeed listen for a ctrl-C and ctrl-break signal, I can see no way to send that signal to a process. This seems to be a fundamental problem in Windows, or am I wrong? I am aware of SendSignal.exe, but so far have been unable to get it to work. It fails as follows:
>SendSignal 26320
Sending signal to process 26320...
CreateRemoteThread failed with 0x00000005.
StartRemoteThread failed with 0x00000005.
0x00000005 == Access is denied.
Trying "taskkill" without -F results in:
>taskkill /PID 24840
ERROR: The process with PID 24840 could not be terminated.
Reason: This process can only be terminated forcefully (with /F option).
All other "kill" functions kill the process immediately rather than sending a signal.
One possible solution would be a file-watch based solution: create a watch for some modification of a specific file. But this is a hack and we would prefer to do it with appropriate signaling. Has anyone solved this issue? It seems to be so very basic a functionality, and it is certainly trivial to do it in a Unix environment. Surely Microsoft has provided SOME mechanism to allow clean shut down of a windowless executable?
I am aware of the thread below, whose question is virtually identical (save for the specification of why the answer is necessary, i.e. why one needs to be able to do this for a windowless, console-less process), but there is no answer there excpet for "use SendSignal", which, as I said, does not work for us:
Can I send a ctrl-C (SIGINT) to an application on Windows?
There are other similar questions, but no answers as yet.
Any help appreciated.
[Upgrading #Anon's comment to an answer for visibility]
windows-kill worked perfectly and managed to resolve access denial issues faced with SendSignal. A privileged user would have to run it as well of course.
windows-kill also supports both ctrl-c and ctrl-break signals.

Stopped service does not release its resources?

I'm trying to deploy a patch to a service I created and replace the service file.
For that reason I need to stop the service so the file will be released.
I'm using sc \\remote stop svcname, then I query the service using sc \\remote query svcname until I see that it's state is STOPPED.
At this point the service file should be unlocked, and to be on the safe side I also delete the service using sc \\remote delete svcname.
Still, it doesn't seem to release the file and any deletion or change attempt fails.
I know one solution might be polling the file repeatedly, but I want to avoid this method.
Any suggestions?
Windows don't ensure the process providing the service terminates when the service is stopped (the process may provide more than one service). It just considers the service stopped when it handles the message sent to it.
So if the service process has a bug and does not properly release resources, they may still be locked. I would probably wait a little and than simply terminate the process.
There is also a tool from Microsoft called handle.exe (this is command-line version, they also have a GUI-one) that can list which processes hold the file open. It should be possible to get the same information programmatically, but I am not sure of the exact calls to make (and you need administrator privileges; you have to give them to the tool too). That way you can check whether the file is open, by which process and wait for it to terminate or force-terminate it if you didn't know which one it is.

How to list Windows Services from within a Service

sc query state= all works as expected from the command line.
From within another Service, sc query state= all doesn't print anything to that sub-process' stdout (captured by the parent, of course).
Is there a permission/privilege that the Service needs in order to list/start/stop the other servies?
A little background: I am making a service that periodically restarts some misbehaving services.
Well, for one don't do that, at least not in a blocking manner. In order for your own service to respond to the SCM (Service Control Manager) in order to return its status, the service has to be able to execute its dispatcher code. This means that if you call this program and wait for it to exit you'll wait indefinitely. One way to mitigate this would be to put this into a separate thread so it's not blocking your dispatching and your service will continue to talk to the SCM.
Alternatively (and probably better) you could use the EnumServicesStatusEx function to talk to the SCM and inquire about the statuses of other services yourself. The function itself doesn't mention anything about being blocking, so you'd have to figure out yourself whether it is and then use a thread again to prevent your service from stopping to talk to the SCM.
One last note: if those misbehaving services are yours, you should more likely fix the respective code. I've had a share of legacy code and had one misbehaving service which got its own helper application as "fault action" (can be configured in service configuration as SERVICE_CONFIG_FAILURE_ACTIONS) that would go about and restart the service whenever it crashed. Once I took that code over, figured out the cause and fixed it, the service was stable again and that application isn't really needed anymore.

Restarting a windows service

I want to schedule a restart of my custom services
automatically using a batch file with net stop, net start.
When net stop runs does it abort anything that is being done
immediately?
Just wondering what will happen if in the middle of processing?
Malcolm
It will call into your code asynchronously and it will be up to you to deal with it. You could enact a clean or abort as you see fit.
It really depends on how the service is implemented. "net stop" essentially calls into the service and says "would you kindly stop". Most services will comply with this command and stop in a timely fashion. However there are the bad services which do not comply and refuse to stop. In this case, net stop will take no further action.
It really depends on the service. I suspect most will try to get into a good state before stopping. It isn't a kill.
A service registers to receive events (via RegisterServiceCtrlHandler). When you do a net stop the registered callback will receive a callback with the SERVICE_CONTROL_STOP operation. How the service responds to that callback is up to the service implementation. It would make sense for the service to do regular application shutdown processing.
Like the others said, when you call net stop, it will invoke the OnStop in the Windows Service. If the OnStop does not kill all the threads in the app, or doesn't shut everything down properly, your service might not stop. (I've seen this happen in one of our WCF services: we didn't close the ServiceHost in OnStop, and therefore, the app would not stop at our command - we'd have to kill the process by hand.)
One common pattern I've seen is to try calling stop on the service, and if it doesn't die within a timeout (10 seconds), kill the process by force. As an alternative to batch files, PowerShell has some pretty good support for dealing with services.

Resources