exit and _exit
- C course
- Advanced
- Lesson 11/83
- 5 min
Learn the difference between exit and _exit.
exit and _exit
exit(status) terminates the process. It first calls functions registered with atexit, then flushes stdio buffers, and finally exits to the kernel.
_exit(status) does a direct kernel exit; it does not flush buffers or call atexit functions. After fork, using _exit in the child before exec is safer; because stdio buffers may be shared with the parent.
atexit functions
atexit(fn) registers a function to be called when the process exits normally. When exit is called, these functions run in reverse order of registration.
You can register up to 32 functions (varies across systems). _exit or signal termination does not call atexit functions. So registering cleanup with atexit is a safe approach: it works with both return and exit.
Practice Cleanup with atexit
Write void farewell(void) containing printf("goodbye\n");. In main, register it with atexit(farewell);. Print printf("merhaba\n"); and exit with exit(0);.
Starter code
#include <stdio.h>
#include <stdlib.h>
// Write farewell function
// Register with atexit
// Call exit
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <stdlib.h>
void farewell(void) {
printf("goodbye\n");
}
int main(void) {
atexit(farewell);
printf("merhaba\n");
exit(0);
}Expected output
merhaba goodbye
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match exit functions
| Term | Meaning |
|---|---|
exit |
Flushes buffers |
_exit |
Exits immediately |
atexit |
Registers function |
return |
Ends function |
2 What is the difference between _exit and exit?
- _exit returns
- exit is faster
- _exit does not flush buffers Correct answer
- exit sends a signal
Explanation: _exit does a direct kernel exit without flushing buffers.
3 atexit registration
atexit(____);
exit(0);
atexit(farewell);
exit(0);
Explanation: The farewell function is registered with atexit.