Jump to content
  • Advertisement
Sign in to follow this  
Endemoniada

Exiting Console App ?

This topic is 3006 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!