Difference between exit() and _Exit() in C++

exit() and _Exit() functions are used to terminate a C++ program. But there must be some difference between these two otherwise what is the use of defining two functions that perform the same task. We will see the difference between these two functions in C++ further in this tutorial.

The key difference between exit() and _exit() function lies in the fact that exit() function performs some cleanup tasks before terminating the program. These include clearing the buffer, terminating the connection, etc. On the other hand _exit() does not perform any such cleaning operation. It simply terminates the program. _Exit() function does not make any call to object destructors or the functions registered with atexit() or at_quick_exit() functions.

See the below codes to clear any misunderstanding.

C++ program for exit():

#include <iostream>
#include <bits/stdc++.h> 

using namespace std;

void fun()
{
  cout << "Function \n";
}

int main()
{
  atexit(fun);
  
  cout << "Calling exit()" << endl;
  
  exit(0);
  
}

Output:

Calling exit()
Function

C++ program for _Exit():

#include <iostream>
#include <bits/stdc++.h> 

using namespace std;

void fun()
{
  cout << "Function \n";
}

int main()
{
  atexit(fun);
  
  cout << "Calling _Exit()" << endl;
  
  _Exit(0);
  
}

Output:

Calling _Exit()

You can see from both outputs that exit() calls function fun() which is defined in the program because it was registered to be called before the program terminates. Whereas function _Exit() does not call fun() and terminates the program.

Thank you.

Also read: Difference between std::quick_exit and std::abort in C++

Leave a Reply

Your email address will not be published. Required fields are marked *