Question

If I call exit() implicitly:

int main(){
  return 0; /*exit(0) is being called */
}

or explicitly:

int main(){
  exit(0);
  return 0; /* this is never reached */
}

The end-point is the same: exit() is being called. Now according to some sources, exit() will make the process do some cleanup before handing control back to the OS.

I know that eventually the kernel(the OS) is going to release all the resources. So what is so special with the process cleaning up before giving control to the kernel? What is excactly this cleanup? Why is it neccesary? How does the process know what to cleanup?

Was it helpful?

Solution

As ever, this question can be solved with reference to the C specification (N1256). 7.20.4.3 Gives this definition for exit():


3. First, all functions registered by the atexit function are called, in the reverse order of their registration except that a function is called after any previously registered functions that had already been called at the time it was registered. If, during the call to any such function, a call to the longjmp function is made that would terminate the call to the registered function, the behavior is undefined.

4. Next, all open streams with unwritten buffered data are flushed, all open streams are closed, and all files created by the tmpfile function are removed.

5. Finally, control is returned to the host environment. If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.


Or in English:

First call all registered atexit functions. Next flush all unwritten buffered data. Next close open streams. Finally, return the exit status and control to the OS.

OTHER TIPS

The C runtime library supports running user code when the process exits, set using the atexit() function. This is not something the underlying operating system knows about, so the code in exit() needs to implement this, for instance.

This is OS-specific, but typically on modern platforms, open files will be closed and their in-process (stdio) buffers flushed. Other cleanup will be handled OS-side.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top