A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
exit terminates the program immediately. It flushes and closes all open streams, calls functions registered with atexit, and returns a status code to the parent process. The status code is how your program communicates success or failure to the shell, to scripts, to process supervisors. exit(0) or exit(EXIT_SUCCESS) means success. exit(1) or exit(EXIT_FAILURE) means failure. Any nonzero value is an error. The specific value can encode what kind of error.
#include <stdio.h>#include <stdlib.h>void cleanup(void) {printf("atexit handler: cleaning up resources\n");}int main(int argc, char *argv[]) {atexit(cleanup);if (argc < 2) {fprintf(stderr, "Usage: %s <filename>\n", argv[0]);exit(EXIT_FAILURE);}FILE *fp = fopen(argv[1], "r");if (fp == NULL) {perror("fopen");exit(EXIT_FAILURE);}printf("File opened successfully.\n");fclose(fp);printf("Exiting normally.\n");exit(EXIT_SUCCESS);}
The atexit handler ran in both cases. exit calls all registered handlers in reverse registration order before terminating. The shell captures the exit status in $?. A status of 1 tells the shell the program failed. A status of 0 tells it everything worked. Shell scripts use this to chain commands: if ./exit_demo file.txt; then echo "success"; fi.
return 0 from main is equivalent to exit(0). Both flush streams, call atexit handlers, and return the status to the parent. The difference: exit can be called from any function, not just main. If a deeply nested utility function detects a fatal error, it can call exit directly rather than propagating an error code up through ten layers of callers. This is acceptable for truly fatal errors. For recoverable errors, return an error code and let the caller decide.
Exit codes are the contract between your program and the outside world. Scripts depend on them. Monitoring systems alert on them. CI pipelines fail on them. Use them deliberately. Next: the time library, for timestamps, durations, and measuring performance.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.