![]() |
VOOZH | about |
The C exit(), abort(), and assert() functions are all used to terminate a C program but each of them works differently from the other. In this article, we will learn about exit, abort, and assert functions and their use in C programming language.
The C exit() function is a standard library function used to terminate the calling process. When exit() is called, any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal.
It is defined inside the <stdlib.h> header file.
void exit(int status);
The exit() function in C only takes a single parameter status which is the exit code that is returned to the caller i.e. either the operating system or parent process. There are two valid values we can use as the status each having a different meaning. They are as follows:
Note: We can actually return any non-zero return value in case of failure.
Error opening file
When called, the exit() function in C performs the following operations:
Exit code: 15
Explanation
In the above function, instead of 9999, the status value is 15. It is an effect of 8-bit integer overflow. After 255 (all 8 bits set) comes 0. As the exit() supports only 8-bit integer values, the output is "exit code modulo 256". The output above is actually the modulo of the value 9999 and 256 i.e. 15.
The C standard atexit() function can be used to customize exit() to perform additional actions at program termination.
The C abort() function is the standard library function that can be used to exit the C program. But unlike the exit() function, abort() may not close files that are open. It may also not delete temporary files and may not flush the stream buffer. Also, it does not call functions registered with atexit().
void abort(void);
Output
timeout: the monitored command dumped core /bin/bash: line 1: 35 Aborted
Note: If we want to make sure that data is written to files and/or buffers are flushed then we should either use exit() or include a signal handler for SIGABRT.
The C assert() function is a macro defined inside the <assert.h> header file. It is a function-like macro that is used for debugging. It takes an expression as a parameter,
void assert(expression);
If the identifier NDEBUG ("no debug") is defined with #define NDEBUG then the macro assert does nothing. Common error output is in the form: Assertion failed: expression, file filename, line line-number.
Output
test.c:7: open_record: Assertion `record_name != ((void *)0)' failed. timeout: the monitored command dumped core /bin/bash: line 1: 34 Aborted