FORK(2) Linux Programmer's Manual FORK(2)

名前

fork - 子プロセスを生成する

書式

#include <sys/types.h>
#include <unistd.h>

pid_t fork(void);

説明

fork() は呼び出し元プロセスを複製して新しいプロセスを生成する。新しいプロセスは「子」プロセスと呼ばれ、呼び出し元プロセスは「親」プロセスと呼ばれる。

The child process and the parent process run in separate memory spaces. At the time of fork() both memory spaces have the same content. Memory writes, file mappings (mmap(2)), and unmappings (munmap(2)) performed by one of the processes do not affect the other.

The child process is an exact duplicate of the parent process except for the following points:

上記のリストにあるプロセス属性は、POSIX.1 で全て指定されている。 親プロセスと子プロセスは、以下の Linux 固有のプロセス属性も異なる:

以下の点についても注意すること:

返り値

成功した場合、親プロセスには子プロセスの PID が返され、 子プロセスには 0 が返される。 失敗した場合、親プロセスに -1 が返され、子プロセスは生成されず、 errno が適切に設定される。

エラー

A system-imposed limit on the number of threads was encountered. There are a number of limits that may trigger this error:
  • the RLIMIT_NPROC soft resource limit (set via setrlimit(2)), which limits the number of processes and threads for a real user ID, was reached;
  • the kernel's system-wide limit on the number of processes and threads, /proc/sys/kernel/threads-max, was reached (see proc(5));
  • the maximum number of PIDs, /proc/sys/kernel/pid_max, was reached (see proc(5)); or
  • the PID limit (pids.max) imposed by the cgroup "process number" (PIDs) controller was reached.
呼び出し元は、スケジューリングポリシー SCHED_DEADLINE で動作しており、かつ reset-on-fork フラグがセットされていない。 sched(7) 参照。
メモリーが足りないために、 fork() は必要なカーネル構造体を割り当てることができなかった。
An attempt was made to create a child process in a PID namespace whose "init" process has terminated. See pid_namespaces(7).
fork() はこのプラットフォームではサポートされていない (例えば、メモリー管理ユニット (MMU) がないハードウェア)。
System call was interrupted by a signal and will be restarted. (This can be seen only during a trace.)

準拠


POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD.

注意

Linux では、 fork() を 書き込み時コピー (copy-on-write) ページを用いて実装している。 したがって、fork を行うことの唯一のデメリットは、 親プロセスのページテーブルを複製と 子プロセス自身のタスク構造の作成のための時間とメモリーが必要なことである。

glibc 2.3.3 以降では、 NPTL スレッド実装の一部として提供されている glibc のfork() ラッパー関数は、 カーネルの fork() システムコール を起動するのではなく、clone(2) を起動する。 clone(2) に渡すフラグとして、伝統的な fork() システムコールと 同じ効果が得られるようなフラグが指定される (fork() の呼び出しは、 flagsSIGCHLD だけを指定して clone(2) を呼び出すのと等価である)。 glibc のラッパー関数は pthread_atfork(3) を使って設定されている 任意の fork ハンドラーを起動する。

pipe(2) および wait(2) を参照。

関連項目


clone(2), execve(2), exit(2), setrlimit(2), unshare(2), vfork(2), wait(2), daemon(3), pthread_atfork(3), capabilities(7), credentials(7)

この文書について

この man ページは Linux man-pages プロジェクトのリリース 5.10 の一部である。プロジェクトの説明とバグ報告に関する情報は https://www.kernel.org/doc/man-pages/ に書かれている。

2020-06-09 Linux