Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

c - Windows console application - signal for closing event

In windows console application, one can catch pressing ctrl+c by using:

#include <stdio.h>
#include <signal.h>

void SigInt_Handler(int n_signal)
{
    printf("interrupted
");
}

int main(int n_arg_num, const char **p_arg_list)
{
    signal(SIGINT, &SigInt_Handler);
    getchar(); // wait for user intervention
}

This works well, except it does not work at all if the user presses the cross × that closes the console window. Is there any signal for that?

The reason I need this is I have this CUDA application which tends to crash the computer if closed while computing something. The code is kind of multiplatform so I'd prefer using signals rather than SetConsoleCtrlHandler. Is there a way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The correct one is SIGBREAK, you can try it with:

#include <stdio.h>
#include <signal.h>

void SigInt_Handler(int n_signal)
{
    printf("interrupted
");
    exit(1);
}

void SigBreak_Handler(int n_signal)
{
    printf("closed
");
    exit(2);
}

int main(int n_arg_num, const char **p_arg_list)
{
    signal(SIGINT, &SigInt_Handler);
    signal(SIGBREAK, &SigBreak_Handler);
    getchar(); // wait for user intervention
    return 0;
}

Upon closing the console window, the program will print "closed" and will return 2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...