implement _Fork and refactor fork using it
[musl] / src / process / _Fork.c
1 #include <unistd.h>
2 #include <signal.h>
3 #include "syscall.h"
4 #include "libc.h"
5 #include "lock.h"
6 #include "pthread_impl.h"
7
8 static void dummy(int x) { }
9 weak_alias(dummy, __aio_atfork);
10
11 pid_t _Fork(void)
12 {
13         pid_t ret;
14         sigset_t set;
15         __block_all_sigs(&set);
16         __aio_atfork(-1);
17         LOCK(__abort_lock);
18 #ifdef SYS_fork
19         ret = __syscall(SYS_fork);
20 #else
21         ret = __syscall(SYS_clone, SIGCHLD, 0);
22 #endif
23         if (!ret) {
24                 pthread_t self = __pthread_self();
25                 self->tid = __syscall(SYS_gettid);
26                 self->robust_list.off = 0;
27                 self->robust_list.pending = 0;
28                 self->next = self->prev = self;
29                 __thread_list_lock = 0;
30                 libc.threads_minus_1 = 0;
31                 if (libc.need_locks) libc.need_locks = -1;
32         }
33         UNLOCK(__abort_lock);
34         __aio_atfork(!ret);
35         __restore_sigs(&set);
36         return __syscall_ret(ret);
37 }