Sign in to follow this  
rogerdv

detecting termination signal: win32 and linux

Recommended Posts

I need to detect when the app receives a termination signal, like a kill command in unix platforms, or Ctrl-C, normally closed (dont know if this counts as a termination signal) or terminated via Program manager in Windows. I think there is no portable way to do this. I have googled to find some piece of code but I have found nothing. Can somebody point me to some resource illustrating how to implement this, for windows or linux?

Share this post


Link to post
Share on other sites
Well, in unix I think you'd want to use the signal() function with your own handler to capture a signal (SIGKILL) and handle it however you want.

I haven't written any cross-platform code that deviates from the C or C++ standard, but I think you could just use preprocessing to include either the Unix-specific code or the Windows-specific code in compilation.

Share this post


Link to post
Share on other sites
signal() works in Windows too (For console apps).
From my code:

bool g_bBreak = false;

void OnBreak(int nSig)
{
g_bBreak = true;
}

int main()
{
signal(SIGTERM,OnBreak);
signal(SIGINT,OnBreak);
while(!g_bBreak)
{
Sleep(10);
}
}


I'm not sure if both signals need to be caught, probably not.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Is there anyway to check if a user pressed the [x] button in the console window?
SIGINT works fine for ctrl+c (thanks), but anyway to check for the [x]?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Okay, nvm SIGBREAK works for the [x] button. Thanks!

Share this post


Link to post
Share on other sites
Hmm what is it specifically that you're trying to do? You could maybe just use the atexit() function to install a handler that will be called when the program terminates.

atexit is the portable way of doing this, but for Windows there is also the possibility to handle the WM_QUIT/WM_CLOSE/WM_DESTROY events in the window procedure.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Wow, that's even better, thanks alot man!

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