I'm stopping a service in my application wanted to know what is the usage of
ExitProcess and if I should use it
You should never need to use ExitProcess() to stop a service. In fact, you should never need to use ExitProcess() at all.
Services are deeply intertwined with the SCM, and if a service that it thinks should be running just vanishes it will take some action to repair it. In extreme cases, it will force the system to reboot.
The correct way to stop a service is to use the documented API to ask the SCM to ask the service to stop. It often takes several seconds for this process to complete as the service itself usually needs to a clean shutdown after asking its worker threads to finish up and halt.
The privileges required to interact with the SCM are less dangerous than that required to end an arbitrary process, but neither is usually granted outside of the Administrators group.
Edit: A comment asked about stopping a service from inside itself.
That can be a tough call, especially if the service is in some kind of unfortunate state. The service and the SCM absolutely have to agree that the service is stopping, or the SCM will take the recovery action that was configured for the service.
I do have a complete implementation of a service that might serve as an alternative point of view for how to handle some of these things. It is LuaService and is a framework that allows a (single worker thread) service to be implemented in pure Lua aside from the LuaService executable itself. Its reference manual attempts to fully document the internals, as well as document some of the details of a service's lifetime that are otherwise documented through the interaction of various articles on MSDN.
Look into the OpenSCManager(), OpenService() and ControlService() Windows API calls. Note that your program may not have the necessary permissions to call these, so elevation may be necessary - see Service Security and Access Rights for further information.
There is also an example how to stop a service.
I see that none of the posts here really answers the original question.
RBerteig wrote: "In extreme cases, it will force the system to reboot."
This is nonsense. This might happen if you kill WinLogon.exe, but is not valid for services in general.
If you stop a service from another application you will obviously use
ControlService(mh_Service, SERVICE_CONTROL_STOP, &k_Status);
But what if a service decides that it's work is done and it wants to shut down itself?
The correct way is this (if your service does not run in a shared process):
void cService::Suicide()
{
// Inform the Service Control Manager that the service is stopped now.
SERVICE_STATUS k_Status = {0};
k_Status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
k_Status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
k_Status.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(mh_Service, &k_Status);
ExitProcess(0);
}
I use this code in my service class and it works perfectly on any version of Windows from XP to Windows 10.
!Obviously you should do any cleanup work that is required before calling this function!
ExitProcess is for ending the process itself (much like ExitThread ends a thread). This is used to end a process (program or DLL), though Microsoft don't recommend it for ending a DLL.
If you are trying to stop yourself (you are the process), you can use ExisProcess, though I would recommend a cleaner shutdown, to make sure everything is cleanly stopped. ExitProcess, like ExitThread, stops without unwinding the stack, so no destructors are called.
From within a service, you stop based on an external signal. You could respond to that by calling ExitProcess, but it would probably be better to have some form of shutdown that closes anything necessary and logs this.
Related
Our MFC app hangs during shutdown if any UI Automation client is active (Such as Inspect. Windows Eyes, UI Spy etc.)
The reason is BOOL AFXAPI AfxOleCanExitApp() returns false if any Ole Objects exist. The app then goes into hidden server mode.
I have seen similar posts dealing with Document objects. The general solution is to set the object count to 0, close normally then set the count back in the OnClose of the main frame.
This is a poor solution for UI Automation. It causes memory leaks and invalid objects in the Client app ( Inspect actually crashes after a time).
Has anyone seen a proper way to tell UI clients this server is going away and release all objects?
There is no real good way to shut down graceful. There is no graceful way to stop any server when it is still in use. You can only do necessary cleanup.
You have Connections to you objects. What is graceful if you cut them? You can use CoDisconnectObject for every object. But there is no difference when you terminate the application. Also using this function doesn't reduce the objects lock count! But you can delete the object without getting a crash with an access from the other COM clients.
The draw back: CoDisconnectObject only works for external links. If you have internal COM pointers the object, they are not affected. So those may still use your object...
When you really find every object that has an external connection you can destroy it. And if you have no internal COM-pointers you can delete your objects even with a usage count !=0. But in lots of cases I have other dependent COM-objects that are linked...
The only real good way to terminate gracefully is to stop all applications that use your application as a server first! And exit after this is done... ;)
So if you want to force a shutdown. Disconnect what you can. Free as many resources you know. Than ignore the applications lock count and exit. Memory is freed, even if the debug version will report a leak. Problematic are only other resources (files, mutexes, system objects...) that may need a better handling as closing the application...
Is there some way to detect that a program was ended by windows task manager's "end process"?
I know that its kinda impossible to do that from within the application being ended (other than to build your app as a driver and hook ZwTerminateProcess), but I wonder if there is a way to notice it from outside.
I don't want to stop the program from terminating, just to know that it was ended by "end process" (and not by any other way).
There might be a better way - but how about using a simple flag?
Naturally, you'd have to persist this flag somewhere outside of the process/program's memory - like the registry, database, or file system. Essentially, when the app starts up, you set the flag to 'True' when the app shuts down through the normal means, you set the flag to 'False'.
Each time the application starts you can check the flag to see if it was not shut down correctly the previous time it was executed.
Open up a handle to the process with OpenProcess, and then wait on that handle using one of the wait functions such as WaitForSingleObject. You can get the exit status of the process using GetExitCodeProcess. If you need your program to remain responsive to user input while waiting, then make sure to wait on a separate thread (or you can periodically poll using a timeout of zero, but remember the performance consequences of polling -- not recommended).
When you're done, don't forget to call CloseHandle. The process object won't be fully deleted from the OS until all of its handles are closed, so you'll leak resources if you forget to call CloseHandle.
Note that there's no way to distinguish between a process exiting normally or being terminated forcefully. Even if you have a convention that your program only ever exits with a status of 0 (success) or 1 (failure) normally, some other process could call TerminateProcess(YourProcess, 1), and that would be indistinguishable from your ordinary failure mode.
According to the documentation, ExitProcess calls the entry point of all loaded DLLs with DLL_PROCESS_DETACH, whereas TerminateProcess does not. (Exiting the main function results in a call to ExitProcess, as do most unhandled exceptions.)
You might also want to look into Application Recovery and Restart.
One option might be to create a "watchdog" application (installed as a service, perhaps) that monitors WMI events for stopping a process via the ManagementEventWatcher class (in the System.Management namespace).
You could query for the death of your process on an interval or come up with some event driven way to alert of your process's demise.
Here's sort of an example (it's in C# though) that could get you started.
Is it possible to have a program restart automatically if it crashes?
Something like:
An unhandled exception is thrown.
Release all resources allocated by process.
Start over and call main.
I would like this behavior for a server application I'm working on. If clients miss use the server it can get a std::bac_alloc exception, in which case I would like the server to simply restart instead of crashing and shutting down, thus avoiding manual startup.
I've done this before in Windows by running said program from another program via a win32 CreateProcess call. The other program then waits on the "monitored" process to exit, and calls its CreateProcess() again if it does. You wait for a process to exit by performing a WaitForSingleObject on the process' handle, which you get as one of the return values from your CreateProcess() call.
You will of course want to program in some way to make the monitoring process shut itself and its child process down.
Let Windows be your watchdog. You can call ChangeServiceConfig2 to set the failure actions for your service. (If your server isn't a service, then you're doing it wrong.) Specify SERVICE_CONFIG_FAILURE_ACTIONS for the dwInfoLevel parameter, and in the SERVICE_FAILURE_ACTIONS structure, set lpsaActions to an array of one or more SC_ACTION values. The type you want is SC_ACTION_RESTART.
I did something similar by implementing a watchdog. The watchdog ran as a service and would wait for a ping (called petting the dog) from the monitored process. If the monitored process died due to an exception, watchdog would cleanup and relaunch the application.
In case the application was not responding(no ping in a certain time) the watchdog would kill it and then restart it.
Here is a link to an implementation that you might want to use:
http://www.codeproject.com/KB/security/WatchDog.aspx
(PS: I implemented my own version but I cannot post it here. I found this from a quick google search and have no first hand experience with this particular implementation.)
If you just catch the exception, it should be possible to just restart your server by internal programming logic without completely restarting the whole program.
Like #T.E.D., we've done this in an application we built. Our application is a windows service, so the helper program stops the service (eventually kill it, if it hangs) and start the service again.
In C++, I have a resource that is tied to a pid. Sometimes the process associated with that pid exits abnormally and leaks the resource.
Therefore, I'm thinking of putting the pid in the file that records the resource as being in use. Then when I go to get a resource, if I see an item as registered as being in use, I would search to see whether a process matching the pid is currently running, and if not, clean up the leaked resource.
I realize there is a very small probability that a new unrealated pid is now sharing the same number, but this is better than leaking with no clean up I have now.
Alternatively, perhaps there is a better solution for this, if so, please suggest, otherwise, I'll pursue the pid recording.
Further details: The resource is a port number for communication between a client and a server over tcp. Only one instance of the client may use a given port number on a machine. The port numbers are taken from a range of available port numbers to use. While the client is running, it notes the port number it is using in a special file on disk and then cleans this entry up on exit. For abnormal exit, this does not always get cleaned up and the port number is left annotated as being in use, when it is no longer being used.
To check for existence of process with a given id, use kill(pid,0) (I assume you are on POSIX system). See man 2 kill for details.
Also, you can use waitpid call to be notified when the process finishes.
I would recommend you use some kind of OS resource, not a PID. Mutexes, semaphores, delete-on-close files. All of these are cleaned up by the OS when a process exits.
On Windows, I would recommend a named mutex.
On Linux, I would recommend using flock on a file.
How about a master process that starts your process (the one which terminates abnormally) waits for your process to crash (waitpid) and spawns it again when waitpid returns.
while(1) {
fork exec
waitpid
}
The problem domain isn't clear, unfortunately, you could try re-explaining it in some other way.
But if I understand you correctly, you could create a map like
std::map< ProcessId, boost::shared_ptr<Resource> > map;
// `Resource` here references to some abstract resource type
// and `ProcessId` on Windows system would be basically a DWORD
and in this case you simply have to list every running process (this can be done via EnumProcesses call on Windows) and remove every entry with inappropriate id from your map. After doing this you would have only valid process-resource pairs left. This action can be repeated every YY seconds depending on your needs.
Note that in this case removing an item from your map would basically call the corresponding destructor (because, if your resource is not being used in your code somewhere else, it's reference count would drop to zero).
The API that achieves that on windows are OpenProcess which takes process ID as input, and GetExitCodeProcess which returns STILL_ACTIVE when the process is, well, still active. You could also use any Wait function with zero timeout, but this API seems somewhat cleaner.
As other answers note, however, this doesn't seem a promising road to take. We might be able to give more focused advice if you provide more scenario details. What is your platform? What is the leaked resource exactly? Do you have access to the leaking app code? Can you wrap it in a high-level try-catch with some cleanup? If not, maybe wait on the leaker to finish with a dedicated thread (or dedicated process altogether)? Any detail you provide might help.
My understanding is that when you kill a C++ application through Task Manager in Windows XP, the application is still "cleanly" destructed - i.e. the call stack will unwind and all the relevant object destructors will be invoked. Not sure if my understanding is wrong here.
Is it possible to kill such an application immediately, without unwinding the stack?
For example, the application may employ RAII patterns which will destroy or release resources when an object is destructed. If the traditional "kill process" through Task Manager is graceful, providing a way to kill the application immediately would allow me to test ungraceful shutdown (e.g. a power outage).
Edit:
Just to clarify, I was after an existing utility or program that would allow me to do this. I should be able to use the solution on programs that I don't have the source code for, meaning that a programmatic solution is not really acceptable.
Edit:
Just to provide more context, sometimes I have to work with 3rd party services which are very intrusive (e.g. nagging me to reboot every hour). Since I know that I don't need to reboot, I want to kill the process/service so it doesn't nag me anymore. Unfortunately some of the 3rd party developers were "smart" enough to prevent me from doing this, and when I kill the process through Task Manager, the system will reboot immediately (I'm guessing that are using RAII to achieve this).
I believe task manager tries a "nice" shutdown by sending a WM_CLOSE message, then if the application doesn't respond it's killed.
This call should kill the process immediately with no warning:
TerminateProcess
e.g.:
TerminateProcess(GetCurrentProcess(), 1);
Update:
You may find this article interesting:
Quitting time: exiting a C++ program
Update 2:
I should be able to use the solution on programs that I don't have the source code for
Hmm, well this is undesirable behavior 99.9% of the time.
SysInternals has a utility called pskill:
http://technet.microsoft.com/en-us/sysinternals/bb896683.aspx
but I'm not sure how "nice" it is.
You might need to roll your own, but it should be pretty easy:
DWORD pid = <get pid from command line>;
TerminateProcess(OpenProcess(PROCESS_TERMINATE, FALSE, pid));
The standard Windows way to do this, without relying on 3rd-party tools, is to use taskkill /f:
taskkill /f <process-id>
taskkill /f /im <process-executable-name>
/f means "force" here, and ensures that process is terminated unconditionally and immediately, with no query or warning.
Unless I'm terribly mistaken (and I just did a little testing to confirm), Task Manager tries to close programs in different ways depending on which tab you're using. If going through the Applications tab and pressing End Task, it will try to close the program cleanly by first sending a WM_CLOSE. But if going through the Processes tab and pressing End Process, it seems to use something along the lines of TerminateProcess, which means no stack unwinding and such.
So first, if you aren't using End Process on the Processes tab, try that.
If that's what you already tried and their software still manages to reboot the system somehow, then there is something more complicated going on. Other people may be on the right track about there being additional processes.
I believe the C standard library method exit(0); will do exactly that, abort the program without calling any destructors, deallocators, etc.
Try that, and let me know if it meets your needs?
It looks like abort() will give you an abnormal exit.
ANSI 4.10.4.1 The behavior of the abort function with regard to open and temporary files
The abort function does not close files that are open or temporary. It does not flush stream
buffers
[source]
and
Abort current process
Aborts the process with an abnormal program termination.
The function generates the SIGABRT signal, which by default causes the program to terminate >returning an unsuccessful termination error code to the host environment.
The program is terminated without executing destructors for objects of automatic or static
storage duration, and without calling any atexit function.
The function never returns to its caller.
[source]
I would try PSKill as suggested by Tim above. I would guess that this will fail as well. If the 3rd party services are really serious about avoiding death, then the service definition may be set to "reboot on crash". The other common approach is to have another service that watchdogs the primary one. The primary service usually sets a global event or employs some other notification mechanism that the watchdog service watches. If the primary service doesn't notify the watchdog, then the watchdog restarts the computer.
The aptly named Kill Tool, available from Microsoft Download. Is part of the Windbg suite also.
The Kill tool, kill.exe, terminates
one or more processes and all of their
threads. This tool works only on
processes running on the local
computer.
kill /f <process>
For example, kill /f lsass (just kidding, do not kill LSA!).
If you want to roll your own, TerminateProcess is the way to go.
The C function abort() in the standard library will instantly kill your application with no cleanup.
C++ defines a standard global function terminate(). Calling it will also instantly exit your application.
Technically terminate()'s behavior could be overridden by the set_terminate function. It calls abort by default.
There are utilities around that can forbid reboot.
HideToolz does that for example -- there is a checkbox buried somewhere that will make it ask you when something initiates reboot. It is detected by many antiviruses as rootkit (which it is, but this one is supposedly tame), so it might be probematic to run on systems you don't have full control over (when antivirus mandated by domain policy, etc)
Extending Pavel's answer:
HANDLE launch(string filename, string params)
{
auto ftemp = wstring(filename.begin(), filename.end());
LPCWSTR f = ftemp.c_str();
auto ptemp = wstring(params.begin(), params.end());
LPCWSTR p = ptemp.c_str();
SHELLEXECUTEINFO ShRun = { 0 };
ShRun.cbSize = sizeof(SHELLEXECUTEINFO);
ShRun.fMask = SEE_MASK_NOCLOSEPROCESS;
ShRun.hwnd = NULL;
ShRun.lpVerb = NULL;
ShRun.lpFile = f;
ShRun.lpParameters = p;
//ShRun.nShow = SW_SHOW;
ShRun.nShow = SW_HIDE;
ShRun.hInstApp = NULL;
if (!ShellExecuteEx(&ShRun))
{
//Failed to Open
}
return ShRun.hProcess;
}
void kill(string filename)
{
launch("taskkill.exe", "/f /im " + filename);
}
void main()
{
kill("notepad.exe"); //Kills all instance of notepad
}