Browse Source

add atexit()

K. Lange 2 years ago
parent
commit
6a76b257f4
4 changed files with 26 additions and 2 deletions
  1. 4 0
      base/usr/include/stdlib.h
  2. 1 1
      libc/main.c
  3. 19 0
      libc/stdlib/atexit.c
  4. 2 1
      libc/unistd/exit.c

+ 4 - 0
base/usr/include/stdlib.h

@@ -29,6 +29,10 @@ extern long int strtol(const char * s, char **endptr, int base);
 extern void srand(unsigned int);
 extern int rand(void);
 
+#define ATEXIT_MAX 32
+extern int atexit(void (*h)(void));
+extern void _handle_atexit(void);
+
 #define RAND_MAX 0x7FFFFFFF
 
 extern void abort(void);

+ 1 - 1
libc/main.c

@@ -125,6 +125,6 @@ void pre_main(int (*main)(int,char**), int argc, char * argv[]) {
 		__argv = argv;
 	}
 	_init();
-	_exit(main(argc, argv));
+	exit(main(argc, argv));
 }
 

+ 19 - 0
libc/stdlib/atexit.c

@@ -0,0 +1,19 @@
+#include <stdlib.h>
+
+static void (*_atexit_handlers[32])(void) = {NULL};
+static int _atexit_count = 0;
+
+void _handle_atexit(void) {
+	if (!_atexit_count) return;
+	do {
+		_atexit_count--;
+		_atexit_handlers[_atexit_count]();
+	} while (_atexit_count);
+}
+
+int atexit(void (*h)(void)) {
+	if (_atexit_count == ATEXIT_MAX) return 1;
+	_atexit_handlers[_atexit_count++] = h;
+	return 0;
+}
+

+ 2 - 1
libc/unistd/exit.c

@@ -1,6 +1,7 @@
 #include <unistd.h>
+#include <stdlib.h>
 
 void exit(int val) {
-	// TODO call exit cleanup handlers (including flushing buffers?)
+	_handle_atexit();
 	_exit(val);
 }