Reputation:
All,
I want to develop an exit handler in my program.
I'm really new to C; is it all about managing signals in C?
How do I know if my program ended in a good way or not?
If not, how do I get the maximum information when exiting?
Upvotes: 4
Views: 13035
Reputation: 4462
C (C89 and C99 standards) provides atexit()
to register function to be called when the program exits. This has nothing to do with signals. Unlike signal handlers, you can register multiple exit handlers. The exit handlers are called in reverse order of how they were registered with atexit()
.
The convention is that when program exits cleanly it returns exit status 0
. This can be done by return 0
from main()
or exit(0)
from anywhere in your program.
In Unix/Linux/POSIX type operating system (not sure of Windows), the parent process get exit status information about the child process using wait()
system call or its variants.
Example: Here is a simple program and its output to demonstrate atexit()
:
#include <stdlib.h>
#include <stdio.h>
static void exit_handler1(void)
{
printf("Inside exit_handler1()!n");
}
static void exit_handler2(void)
{
printf("Inside exit_handler2()!n");
}
int main(int argc, char *argv[])
{
atexit(exit_handler1);
atexit(exit_handler2);
return 0;
}
Output generated by the program:
Inside exit_handler2()!
Inside exit_handler1()!
Upvotes: 13
Reputation: 1220
Look here you will find all what you want: http://www.cplusplus.com/reference/cstdlib/exit/
I added a new link here take a look:
Exception libraries for C (not C++)
Upvotes: 0
Reputation: 1139
If i am not get wrong you ask about giving back results from program when exiting. You should use exit(x);
function to return value from your program. You can put any integer value as parameter x
. And dont forget to use #include <stdlib.h>
in your program start.
Upvotes: 0