abort function in c

Use of abort function in C/C++ with Examples

The abort function terminates the execution of a current process abnormally. When the abort function is called it raises the SIGABRT signal to cause abnormal termination of the current process.

The abort function defined in the ‘stdlib.h’ header file, so you have to include the header file before using it.

Syntax abort in C:

//Syntax of abort in c

void abort(void);            (until C11)



_Noreturn void abort(void);   (since C11)

Parameters:

Does not takes any parameter.

Return:

Does not return any value.

 

Let’s see an example code to understand the abort function in C. This example code tests for the successful opening of the file aticleworld.txt. If an error occurs, an error message is printed, and the program ends with a call to the abort() function.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fptr = fopen("aticleworld.txt","r");
    if (fptr == NULL)
    {
        fprintf(stderr, "Failed to open the file\n");
        abort();
    }

    /* Normal processing continues here. */
    fclose(fptr);
    printf("Normal Return\n");

    return 0;
}

Output:

Let us compile and run the above program that will produce the following result when it tries to open the aticleworld.txt file, which does not exist,

abort function in c

Some important points related to abort() function in C:

 

1. You must include stdlib.h header file before using the abort function in C.

2. It does not call functions registered with atexit().

3. Whether open resources such as files are closed is implementation-defined.

4. Whether open streams with unwritten buffered data are flushed or temporary files are removed is implementation-defined.

5. An implementation-defined status is returned to the host environment that indicates unsuccessful execution.

6. abort() is the thread-safe functions from the standard c library. i.e. function can be called by different threads without any problem.

 

Recommended Articles for you: