C exit(), abort() and assert() Functions
Last Updated :
21 Sep, 2023
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.
1. exit() in C
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.
Syntax of exit() in C
void exit(int status);
Parameters
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:
- 0 or EXIT_SUCCESS: 0 or EXIT_SUCCESS means that the program has been successfully executed without encountering any error.
- 1 or EXIT_FAILURE: 1 or EXIT_FAILURE means that the program has encountered an error and could be executed successfully.
Note: We can actually return any non-zero return value in case of failure.
Return Value
- This function doesn’t return any value to the current process so its return type is void. Instead, it returns the status value to the parent process which is returned through a method different than the return value.
Example 1: C Program to Illustrate the exit() Function
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * pFile;
pFile = fopen ( "myfile.txt" , "r" );
if (pFile == NULL) {
printf ( "Error opening file" );
exit (1);
}
else {
}
return 0;
}
|
Output
Error opening file
How exit() in C works?
When called, the exit() function in C performs the following operations:
- Flushes unwritten buffered data.
- Closes all open files.
- Removes temporary files.
- Returns an integer exit status to the operating system.
Example 2: Passing an integer value greater than 255 to the exit() function in C
C
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main( void )
{
pid_t pid = fork();
if (pid == 0) {
exit (9999);
}
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
printf ( "Exit code: %d\n" , exit_status);
}
return 0;
}
|
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.
2. abort() in C
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().
Syntax of abort() in C
void abort(void);
Parameters
- The C abort() function does not take any parameter and does not have any return value. This function actually terminates the process by raising a SIGABRT signal, and your program can include a handler to intercept this signal.
Return Value
- The abort() function in C does not return any value.
Example: C Program to Illustrate the abort() Function
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fp = fopen ( "C:\\myfile.txt" , "w" );
if (fp == NULL) {
printf ( "\n could not open file " );
getchar ();
exit (1);
}
fprintf (fp, "%s" , "Geeks for Geeks" );
abort ();
getchar ();
return 0;
}
|
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.
3. assert() in C
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,
- If the expression evaluates to 1 (true), the program continue to execute.
- If the expression evaluates to 0 (false), then the expression, source code filename, and line number are sent to the standard error, and then the abort() function is called.
Syntax of assert() in C
void assert(expression);
Parameters
- expression: It is the condition we want to evaluate.
Return Value
- The assert() function does not return any value.
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.
Example: C Program to Illustrate the assert() Function
C
#include <assert.h>
#include <stdio.h>
void open_record( char * record_name)
{
assert (record_name != NULL);
}
int main( void ) { open_record(NULL); }
|
Output
test.c:7: open_record: Assertion `record_name != ((void *)0)' failed.
timeout: the monitored command dumped core
/bin/bash: line 1: 34 Aborted
Similar Reads
atexit() function in C/C++
The function pointed by atexit() is automatically called without arguments when the program terminates normally. In case more than one function has been specified by different calls to the atexit() function, all are executed in the order of a stack (i.e. the last function specified is the first to b
3 min read
C Function Arguments and Function Return Values
Prerequisite: Functions in C A function in C can be called either with arguments or without arguments. These functions may or may not return values to the calling functions. All C functions can be called either with arguments or without arguments in a C program. Also, they may or may not return any
6 min read
exit() vs _Exit() in C/C++
exit() and _Exit() in C/C++ are very similar in functionality. However, there is one difference between exit() and _Exit() and it is that exit() function performs some cleaning before the termination of the program like connection termination, buffer flushes, etc. exit() In C, exit() terminates the
3 min read
fegetexceptflag() function in C/C++
The fegetexceptflag() function in C/C++ is specified in header file fenv.h and gets floating point exception flags. This function store the raised exception in the point specified by flagp . Syntax: int fegetexceptflag(fexcept_t* flagp, int excepts) Parameters: The function accepts two mandatory par
2 min read
Interesting Facts about Macros and Preprocessors in C
In a C program, all lines that start with # are processed by preprocessor which is a special program invoked by the compiler. by this we mean to say that the â#â symbol is used to process the functionality prior than other statements in the program, that is, which means it processes some code before
6 min read
C fopen() Function
In C, the fopen() function is used to open a file in the specified mode. The function returns a file pointer (FILE *) which is used to perform further operations on the file, such as reading from or writing to it. If the file exists then the fopen() function opens the particular file else a new file
5 min read
Assertions in C/C++
Assertions are statements used to test assumptions made by programmers, such as validating logic or invariants in the code. For example, we may use an assertion to check if the index of an array is within valid bounds during development. Following is the syntax for assertion. void assert( int expres
2 min read
exec family of functions in C
The exec family of functions replaces the current running process with a new process. It can be used to run a C program by using another C program. It comes under the header file unistd.h. There are many members in the exec family which are shown below with examples. execvp : Using this command, the
4 min read
User-Defined Function in C
A user-defined function is a type of function in C language that is defined by the user himself to perform some specific task. It provides code reusability and modularity to our program. User-defined functions are different from built-in functions as their working is specified by the user and no hea
6 min read
getdate() and setdate() function in C with Examples
setdate() Method: getdate() function is defined in dos.h header file. This function fills the date structure *dt with the system's current date. Syntax struct date dt; getdate(&dt); Parameter: This function accepts a single parameter dt which is the object of structure date. Return Value: This m
2 min read