exit() vs _Exit() in C and C++

In C, exit() terminates the calling process without executing the rest code which is after the exit() function.

Example:-

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to illustrate exit() function.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    printf("START");
  
    exit(0); // The program is terminated here
  
    // This line is not printed
    printf("End of program");
}

chevron_right


Output:

START

Now the question is that if we have exit() function then why C11 standard introduced _Exit()? Actually exit() function performs some cleaning before termination of the program like connection termination, buffer flushes etc. The _Exit() function in C/C++ gives normal termination of a program without performing any cleanup tasks. For example it does not execute functions registered with atexit.

Syntax:



// Here the exit_code represent the exit status 
// of the program which can be 0 or non-zero.
// The _Exit() function returns nothing.
void _Exit(int exit_code);
filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demonstrate use of _Exit()
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    int exit_code = 10;
    printf("Termination using _Exit");
    _Exit(exit_code);
  
}

chevron_right


Output:


Showing difference through programs:

filter_none

edit
close

play_arrow

link
brightness_4
code

// A C++ program to show difference
// between exit() and _Exit()
#include<bits/stdc++.h>
using namespace std;
  
void fun(void)
{
   cout << "Exiting";
}
  
int main()
{
   atexit(fun);
   exit(10);
}

chevron_right


Output

Exiting

If we replace exit with _Exit(), then nothing is printed.

filter_none

edit
close

play_arrow

link
brightness_4
code

// A C++ program to show difference
// between exit() and _Exit()
#include<bits/stdc++.h>
using namespace std;
  
void fun(void)
{
   cout << "Exiting";
}
  
int main()
{
   atexit(fun);
   _Exit(10);
}

chevron_right


Output


This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : Vishal Vishwakarma



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.