Sign in to follow this  
Endemoniada

Exiting Console App ?

Recommended Posts

Hi guys, I wrote a home-baked server as a Win32 console app that's pretty much like this: int main() { initServer(); while(TRUE){ runServer(); } cleanupServer(); return 0; } It works great but I can never get to the cleanupServer() code. I can make a flag in the while statement but how would I set it ? The only thing I can come up with is having runServer() return a BOOL to perhaps break the loop but then I'd have to send the server a "secret code" to shut it down. Ideally I'd like to use something like scanf() but that blocks. What should I do ? Thanks.

Share this post


Link to post
Share on other sites
have runServer return true or false would be the best way.otherwise set an exit function using _onexit() that does your cleanup and call exit() to stop the program.

Share this post


Link to post
Share on other sites
The simplest way would be to change the loop to poll against keyboard input (_kbhit). If you are on a platform that does not have this function (I know you have a Win32 currently, but if you ever need to port your code), check out an alternative approach.

while(!_kbhit) { runServer(); }

Also, on Windows, you can use the SetConsoleCtrlHandler function to register an event handler that will process the console closing and then break the loop based on a flag you set.


#include <windows.h>
bool bExit = false;

BOOL WINAPI CtrlHandler( DWORD fdwCtrlType )
{
bExit = true;
return TRUE;
}

int main(int argc, char * argv[])
{
SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
while(!bExit)
{
runServer();
}
SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, FALSE);
return 0;
}



If you want to go the approach of being able to remotely close the server by sending it some control message, then you'd simply make runServer return a flag to indicate if it should still be running or not. Then, you just break on the condition when it's done.

while(TRUE) { if(runServer() == FALSE) break; }

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this