Merge remote-tracking branch 'nsz/master'
[musl] / src / exit / exit.c
1 #include <stdlib.h>
2 #include <unistd.h>
3 #include <stdio.h>
4 #include "libc.h"
5 #include "atomic.h"
6 #include "syscall.h"
7
8 static void dummy()
9 {
10 }
11
12 /* __towrite.c and atexit.c override these */
13 weak_alias(dummy, __funcs_on_exit);
14 weak_alias(dummy, __fflush_on_exit);
15
16 void exit(int code)
17 {
18         static int lock;
19
20         /* If more than one thread calls exit, hang until _Exit ends it all */
21         while (a_swap(&lock, 1)) __syscall(SYS_pause);
22
23         /* Only do atexit & stdio flush if they were actually used */
24         __funcs_on_exit();
25         __fflush_on_exit();
26
27         /* Destructor s**t is kept separate from atexit to avoid bloat */
28         if (libc.fini) libc.fini();
29         if (libc.ldso_fini) libc.ldso_fini();
30
31         _Exit(code);
32         for(;;);
33 }