This Tutorial explains the abort() function in C with examples.
What is abort() Function?
abort() Function in C terminates execution of a program abnormally. It’s defined in ‘stdlib.h’ header and is prototyped below
Prototype of abort() Function in C
void abort(void);
Example of abort() Function in C
/* abort.c -- terminates execution abnormally */ #include <stdio.h> #include <stdlib.h> int main(void) { abort(); printf("\"abort() called prior to printf()\"\n"); return 0; }
When “abort()” is called, it raises the “SIGABRT” signal, which results in an abnormal program termination. A handler can be installed by a program to carry out required actions either before or in place of the program’s termination.
The following two functions relate with normal termination of a program.
int atexit(void (*function)(void)); int exit(int status);
- These are defined in ‘stdlib.h’ header.
- ‘atexit()’ registers ‘functions as exit functions’. ‘atexit()’ returns 0 for successfully registring otherwise retuns non-zero.
- When ‘exit()’ function is called, program is about to terminate normally.
- All the functions registered with ‘atexit()’ are called in the reverse order that they were registered.
- Then all buffers are flushed for streams that need it, all open files are closed.
- Any file created with ‘tmpfile()’ is deleted. Recall that ‘tmpfile()’ creates a file for temporary holding the data in a program.
- File is deleted if you explicitly close it or when program is done.
Let’s take a simple C program using ‘atexit()‘ and ‘exit()‘ functions,
/* atexit_exit.c -- program uses 'atexit()' to register functions */ /* as exit() functions */ #include <stdio.h> #include <stdlib.h> void goodbye(void); void okey(void); int main(void) { int ret; /* atexit() registers goodbye() as exit function */ ret = atexit(goodbye); if (ret == 0) puts("atexit() succeeds!"); /* atexit() registers okey() as exit function */ ret = atexit(okey); if (ret == 0) puts("atexit() succeeds!"); exit(0); } void goodbye(void) { puts("goodbye!"); } void okey(void) { puts("okey, bye!"); }
Output follows
atexit() succeeds! atexit() succeeds! okey, bye! goodbye!
Notice that firstly, ‘atexit()’ registered ‘goodbye()’ and ‘okey()’ functions and when ‘exit()’ was called functions registered with ‘atexit()’ called in reverse order of their prior registration and printed massages on stdout. Also, notice that effect of calling ‘exit()’ is same as ‘main()’ returns to host environment. Further, when ‘exit()’ is called, program terminates normally and therefore ‘exit()’ never returns to calling program.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Check C Books
- Apply for Computer Science Internship
- Check Computer Science Books
- Practice BCA MCQs
- Apply for C Internship