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...
Related
I'm using Visual Studio 2013 and programming in C++ / Xaml. I have a worker thread that splits off from the UI thread to do some calculations. I need this worker thread to be able to access components such as a TextBox or a ProgressBar on the user interface to do things like inform the user on its progress. After some research this is apparently way harder than I anticipated.
You may think the worker threads need to access the UI, but you should re-think that idea, it is a bad approach. You already found out that it is way harder than anticipated - look at this as an indicator that you may be on the wrong track.
The better way is to use indirection, i.e. to post a message, raise an event or signal a flag whenever there are new data available to display. The UI thread handles this and does whatever he needs to do when it is appropriate.
This way you leave room for future improvements, e.g. you may wish to replace the graphical UI by some other version (progress bar instead of a percent label) or a completely different UI later (think web-based, think service without own UI, etc).
Having a worker thread accessing controls directly ties your background worker code too closely to a concrete UI, which is nothing more than an arbitrary restriction that comes with no gain1). By using an indirection (this could be even an properly synchronized view model) you prevent this, making later changes a snap.
1 Who says YAGNI? You already need it, right now!
I have a server program which should run full time a day. If I want to change some parameters of it, Is there any way rather than shut down then restart way?
There are quite a few ways of doing this, including, but almost certainly not limited to:
You can maintain the parameters in a separate file so that the program will periodically check that file and update its internal information.
Similar to (1) but you can send some sort of signal to the application to get it to immediately re-read the file.
You can do either (1) or (2) but using shared memory rather than a configuration file.
You can have your program sit at the server end of an IPC conversation, so that a client can open up a connection to it to provide new parameters. Anything from a simple message queue to a full-blown HTTP server and associated pages.
Of course, all of these tend to need a fair amount of work in your program to get it to look for the new information.
You should take that into account when making your decision. By far the quickest solution to implement is to just (cleanly) kill off the process at something like 11:55pm then immediately restart it. It's simpler because your code probably already has the ability to load the information on startup, so this could be a simple cron one-liner.
Some people speak of laziness as a bad thing but that's not always the case :-)
If the Server maintains many alive connections from clients, restarting the server process is the last way you should consider. Except reloading configuration files, inserting a proxy process between clients and server can be another way.
The proxy process is Responsible for 2 things.
a. Maintaining the connection from clients and forwarding packets to Server for handling.
b. Judging weather the current server process(Server A) is alive and if it not, switching to another server(Server B) automatically.
Then you can change parameters by restart server without worrying about interrupting clients since there is always two(or more) servers running.
I made a MFC application which probably has two threads, one for receiving data from a socket using UDP protocol and one is the main thread of MFC app. While any data is received some objects, created in the main thread by new operator, would be notified to fetch the data through apply the observer design pattern. The problem is that sometimes after I clicked the close system button, the GUI of the app disappeared, but its process can still be found in the Task Manager. If I stop the data source (UDP client) this problem would never happen. Other important and maybe helpful information is listed below:
The Observer design pattern was implemented with STL container list. I have used the critical section protection in the Attach, Detach and Notify functions.
I deleted the observer objects before closing the UDP socket.
The data transfer rate may be a little faster than process data, because after closing the data source the data process is still working.
I can't figure out what lead my app can not exit completely. Please give me some clues.
This is usually caused by a thread you created and not exit it programmatically when you exit the appliation. There must be a while clause in your thread. The way to find where it is still running is:
use debug mode to start you application and click the exit button the top right corner to exit it.
Check from task manager and see if it is still running
if it is, excute Debug->Break All,
Open threads windows, double click each thread, you will find where your code is still looping.
Typically a process won't terminate because there's still a foreground thread running somewhere. You must ensure that your socket library isn't running any thread when you want to close your application.
First thing, with MFC, please use the notification based methods to get notifications on message arrivals, connections etc. So you can get rid of threads if you have.
It's quite easy to attache to a debugger and Break see which threads are existing and waiting for what.
Alternatively you can use ProcessExplorer with proper symbol configuration to see the call stacks of the threads available for the particular process.
The application can two kind of issues to exit, one could be infinite loop and other might be waiting/deadlock (e.g. socket read command is a blocking call). You can easily deduce the problem by attaching to debugger.
Otherwise please provide further information about the threads, code snippet possible.
i know little about pipes but have used one to connect two processes in my code in visual C++. The pipe is working well, but I need to add error handling to the same, hence wanted to know what will happen to a pipe if the server creating it crashed and how do I recognize it from client process?
Also what will happen if the client process tried accessing the same pipe, after the server crash, if no error handling is put in place?
Edit:
What impact will be there on the memory if i keep creating new pipes (say by using system time as pipe name) while the previous was broken because of a server crash? Will these broken pipes be removed from the memory?
IIRC the ReadFile or WriteFile function will return FALSE and GetLastError() will return STATUS_PIPE_DISCONNECTED
I guess this kind of handling is implemented in your code, if not you should better add it ;-)
I just want to throw this out there.
If you want a survivable method for transferring data between two applications, you might consider using MSMQ or even bringing in BizTalk or another message platform.
There are several things to consider:
what happens if the server is rebooted or loses power?
What happens if the server application becomes unresponsive?
What happens if the server application is killed or goes away completely?
What is the appropriate response of a client application in each of the above?
Each of those contexts represent a potential loss of data. If the data loss is unacceptable then named pipes is not the mechanism you should be using. Instead you need to persist the messages somehow.
MSMQ, storing to a database, or even leveraging Biztalk can take care of the survivability of the message itself.
If 1 or 3 happens, then the named pipe goes away and must be recreated by a new instance of your server application. If #2 happens, then the pipe won't go away until someone either reboots the server or kills the server app and starts it again.
Regardless, the client application needs to handle the above issues. They boil down to connection failed problems. Depending on what the client does you might have it move into a wait state and let it ping the server every so often to see if it has come back again.
Without knowing the nature of the data and communication processes involved its hard to recommend a proper approach.
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.