C abort()

The abort() function is defined in the stdlib.h header file. It helps to abort the program execution by raising the SIGABRT signal and comes out directly from the place of the call.


void abort(void); 

 

abort() Parameters: 

The abort() function does not take any parameter. The abort() does not flush the open file buffers or call any cleanup functions that we have installed using atexit().

abort() Return Value

The abort() function does not return any parameter. The abort() function overrides blocking or ignoring the SIGABRT signal.

Examples of abort()

Example 1: Working of abort() function in C?


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

int main()
{
   FILE *p;
   
   printf("Open myfile.txt\n");
   p = fopen( "myfile.txt","r" );
   if(p == NULL) {
      printf("Abort the program\n");
      abort();
   }
   printf("Close myfile.txt\n");
   fclose(p);
   
   return(0);
}

Output:


Open myfile.txt                                                    
Abort the program                                                  
Aborted (core dumped)

Example 2: How abort() works in error case?


#include <stdio.h>
#include <stdlib.h>
int main (){
    FILE *p = fopen("mydata.txt","r");
    if (p == NULL) {
       fprintf(stderr, "Opening file mydata.txt have error in function main()\n");
       abort();
    }
 
    /* Normal processing continues here. */
    fclose(p);
    printf("Normal Return\n");
    return 0;
}

Output:


Opening file mydata.txt have error in function main()