Tuesday, April 8, 2008

Shutdown hook for C++

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);
}

2 comments:

Summary said...

In C too i guess it can be implemented. I guess in setitimer.c its been implemented .

http://www.makelinux.net/alp/069.htm

rm5248 said...

atexit() is a function in the stdlib, which means that you can use it in either C or C++(there's no need for a timer).

http://www.cplusplus.com/reference/clibrary/cstdlib/