1 //===-- Linux implementation of fork --------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "src/unistd/fork.h"
11 #include "src/__support/OSUtil/syscall.h" // For internal syscall function.
12 #include "src/__support/common.h"
13 #include "src/__support/threads/fork_callbacks.h"
14 #include "src/__support/threads/thread.h" // For thread self object
16 #include "src/errno/libc_errno.h"
17 #include <signal.h> // For SIGCHLD
18 #include <sys/syscall.h> // For syscall numbers.
20 namespace LIBC_NAMESPACE
{
22 // The implementation of fork here is very minimal. We will add more
23 // functionality and standard compliance in future.
25 LLVM_LIBC_FUNCTION(pid_t
, fork
, (void)) {
26 invoke_prepare_callbacks();
28 pid_t ret
= LIBC_NAMESPACE::syscall_impl
<pid_t
>(SYS_fork
);
29 #elif defined(SYS_clone)
30 pid_t ret
= LIBC_NAMESPACE::syscall_impl
<pid_t
>(SYS_clone
, SIGCHLD
, 0);
32 #error "fork and clone syscalls not available."
35 // Return value is 0 in the child process.
36 // The child is created with a single thread whose self object will be a
37 // copy of parent process' thread which called fork. So, we have to fix up
38 // the child process' self object with the new process' tid.
39 self
.attrib
->tid
= LIBC_NAMESPACE::syscall_impl
<pid_t
>(SYS_gettid
);
40 invoke_child_callbacks();
45 // Error case, a child process was not created.
46 libc_errno
= static_cast<int>(-ret
);
50 invoke_parent_callbacks();
54 } // namespace LIBC_NAMESPACE