我想在用户按下后调用清理功能 小" x"在控制台窗口的右上角。
我已经注册了atexit
方法,但在这种情况下,这不会被调用。
解决方案需要在Windows和Linux上运行。
答案 0 :(得分:1)
你不能在这里使用atexit,因为它会在进程正常终止时被调用,而在你的情况下,进程会被一个信号终止。
在linux
上,当控制终端关闭时,SIGHUP(信号挂断)被发送到进程,您可以使用POSIX信号处理。
在windows
上传递CTRL_CLOSE_EVENT事件,您可以使用SetConsoleCtrlHandler winapi来处理此问题。
因此,据我所知,在c++
中没有独立于平台的方法来处理这个问题。您应该使用平台相关代码来执行此操作,如以下简单程序所示。我在VS的Windows上和使用g ++的ubuntu上测试了它。请注意,为简单起见,省略了错误处理并在信号处理程序中执行了I / O.
程序注册信号处理程序和atexit
函数。然后它睡了10秒钟。如果您未在10秒内关闭控制台,则该过程将正常终止,并且将调用atexit
处理程序。如果你在10秒之前关闭窗口,它将捕获信号。在linux上,你不会看到信号处理程序被调用,但它会被调用,你可以通过写一个文件(或发出一个哔声?)来检查这个,虽然我不推荐它。
#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#ifdef WIN32
BOOL sig_handler(DWORD signum)
{
switch( signum )
{
case CTRL_CLOSE_EVENT:
printf( "Ctrl-Close event\n" );
return( TRUE );
default:
return FALSE;
}
}
#else
void sig_handler(int signum)
{
/* you won't see this printed, but it runs */
printf("Received signal %d\n", signum);
}
#endif
void exit_fn(void)
{
printf("%s\n", __FUNCTION__);
}
void setup_signal_handler()
{
#ifdef WIN32
SetConsoleCtrlHandler((PHANDLER_ROUTINE)sig_handler, TRUE);
#else
struct sigaction sa;
sa.sa_handler = &sig_handler;
sigfillset(&sa.sa_mask);
sigaction(SIGHUP, &sa, NULL);
#endif
}
int main(void)
{
printf("%s\n", __FUNCTION__);
/* setup signal handler */
setup_signal_handler();
/* setup function to be called at normal process termination */
atexit(exit_fn);
/* sleep for 10s */
#ifdef WIN32
Sleep(10000);
#else
sleep(10);
#endif
/* print message if process terminates normally */
printf("Normal process termination\n");
exit(EXIT_SUCCESS);
}