user2122937
user2122937

Reputation:

Exit Handler in C

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

Answers (3)

FooF
FooF

Reputation: 4462

  1. 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().

  2. 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.

  3. 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

Aymanadou
Aymanadou

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

Mahmut Ali &#214;ZKURAN
Mahmut Ali &#214;ZKURAN

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

Related Questions