fork(2) System Calls Manual fork(2) fork - LIBRARY Standard C library (libc, -lc) #include pid_t fork(void); fork() . . . . fork() . , (mmap(2)) (munmap(2)), , . : o , PID ( ) (setpgid(2)) . o . o (mlock(2), mlockall(2)). o (getrusage(2)) 0. o (sigpending(2)). o (semop(2)). o (fcntl(2)) ( , fcntl(2) flock(2)). o (setitimer(2), alarm(2), timer_create(2)). o - (aio_read(3), aio_write(3)) - (. io_setup(2)). POSIX.1. , Linux: o (dnotify) ( F_NOTIFY fcntl(2)). o PR_SET_PDEATHSIG prctl(2) , . o . PR_SET_TIMERSLACK prctl(2). o , MADV_DONTFORK madvise(2), fork() . o , madvise(2) MADV_WIPEONFORK, fork() ( MADV_WIPEONFORK ). o SIGCHLD (. clone(2)). o , ioperm(2), ; ioperm(2). : o The child process is created with a single thread--the one that called fork(). The entire virtual address space of the parent is replicated in the child, including the states of mutexes, condition variables, and other pthreads objects; the use of pthread_atfork(3) may be helpful for dealing with problems that this can cause. o fork() -- ( signal-safety(7)) , execve(2). o . ( open(2)). , , -, ( F_SETOWN F_SETSIG fcntl(2)). o ( mq_overview(7)). . , (mq_flags). o ( opendir(3)). POSIX.1 , ; Linux/glibc . On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set to indicate the error. EAGAIN . , : o RLIMIT_NPROC ( setrlimit(2)), ID ; o , /proc/sys/kernel/threads-max ( proc(5)); o PID, /proc/sys/kernel/pid_max ( proc(5)); o PID (pids.max), cgroup << >> (PID). EAGAIN SCHED_DEADLINE --fork (reset-on-fork). sched(7). ENOMEM fork() - , . ENOMEM PID, <> . pid_namespaces(7). ENOSYS fork() (, - , (MMU)). ERESTARTNOINTR ( Linux 2.6.17) ( ). C Since glibc 2.3.3, rather than invoking the kernel's fork() system call, the glibc fork() wrapper that is provided as part of the NPTL threading implementation invokes clone(2) with flags that provide the same effect as the traditional system call. (A call to fork() is equivalent to a call to clone(2) specifying flags as just SIGCHLD.) The glibc wrapper invokes any fork handlers that have been established using pthread_atfork(3). POSIX.1-2008. POSIX.1-2001, SVr4, 4.3BSD. Linux, fork() << >> (copy-on-write, COW), , , . See pipe(2) and wait(2) for more examples. #include #include #include #include #include int main(void) { pid_t pid; if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) { perror("signal"); exit(EXIT_FAILURE); } pid = fork(); switch (pid) { case -1: perror("fork"); exit(EXIT_FAILURE); case 0: puts("Child exiting."); exit(EXIT_SUCCESS); default: printf("Child is PID %jd\n", (intmax_t) pid); puts("Parent exiting."); exit(EXIT_SUCCESS); } } . clone(2), execve(2), exit(2), setrlimit(2), unshare(2), vfork(2), wait(2), daemon(3), pthread_atfork(3), capabilities(7), credentials(7) Azamat Hackimov , Dmitry Bolkhovskikh , Yuri Kozlov ; GNU 3 , . . , , . Linux man-pages 6.06 31 2023 . fork(2)