Shutdown hook is not a strange for Java people. It's there since JDK 1.3 . But for the C++ I couldn't found similar function. I wrote a simple program to demonstrate the some features of shutdown hook using available function in c++. I think C++ library is rich enough to write a complete shutdown hook. But indeed it bit hard when compare to Java.
When you hit the Ctrl+c following program will call “fnBeforeExit” function before the system get shut.
If you wish you can try this program by replacing never ending loop with “exit(0)”.
//
// File: Newmain.cc
// Author: eranga
//
// Created on April 8, 2008, 3:52 PM
//
#include < stdio.h>
#include < stdlib.h>
#include < iostream>
#include < csignal>
//
// Shut down hook for C++
//
//Shut down function done all the cleanups
void fnBeforeExit(void) {
puts("Exit function calls.");
puts("Do connection close, filde descriptor close...etc in here.");
}
//Function to call when interactive attention signal recieved
//Generally generated by the application user.
void sigint_handler(int sig) {
std::cout << "Exit call ( Ctrl + C ) " << sig << "\n";
exit(0);
}
int main(int argc, char** argv) {
/*
* The function pointed by the function pointer argument is called when the program terminates normally.
* If more than one atexit function has been
* specified by different calls to this function,
* they are all executed in reverse order as a stack,
* i.e. the last function specified is the first to be executed at exit.
* One single function can be registered to be executed at exit more than once.
* C++ implementations are required to support the registration of at least 32 atexit functions.
*/
atexit(fnBeforeExit);
std :: cout << "Program started....." << std::endl;
/*
* Specifies a way to handle signals
* SIGINT - (Signal Interrupt) Interactive attention signal. Generally generated by the application user.
*/
signal(SIGINT, sigint_handler);
while(true){
}
return (EXIT_SUCCESS);
}
Tuesday, April 8, 2008
Subscribe to:
Posts (Atom)