De Programação Avançada no Ambiente UNIX por W. Richard Stevens (pg. 188):
8.3
fork
functionThe only way a new process is created by the Unix kernel is when an existing process calls the
fork
function. (This doesn't apply to the special processes that we mentioned in the previous section—the swapper,init
, and pagedaemon. These processes are created specially by the kernel as part of bootstrapping.)#include <sys/types.h> #include <unistd.h> pid_t fork(void); /* Returns: 0 in child, process ID of child in parent, -1 on error */
The new process created by
fork
is called the child process. The function is called once but returns twice. The only difference in the returns is that the return value in the child is 0 while the return value in the parent is the process ID of the new child. The reason the child's process ID is returned to the parent is because a process can have more than one child, so there is no function that allows a process to obtain the process IDs of its children. The reasonfork
returns 0 to the child is because a process can have only a single parent, so the child can always callgetppid
to obtain the process ID of its parent. (Process ID 0 is always in use by the swapper, so it's not possible for 0 to be the process ID of a child.)Both the child and parent continue executing with the instruction that follows the call to
fork
. The child is a copy of the parent. For example, the child gets a copy of the parent's data space, heap, and stack. Note that this is a copy for the child—the parent and child do not share these portions of memory. Often the parent and child share the text segment (Section 7.6), if it is read-only.
No Linux, o operador fork
do Perl chama o sistema fork
e retorna undef
na falha em vez de -1.
Stevens fornece listas (p. 192) de propriedades herdadas e diferenças entre os processos pais e seus filhos bifurcados:
Besides open files, there are numerous other properties of the parent that are inherited by the child:
- real user ID, real group ID, effective user ID, effective group ID
- supplementary group IDs
- process group ID
- session ID
- controlling terminal
- set-user-ID flag and set-group-ID flag
- current working directory
- root directory
- file mode creation mask
- signal mask and dispositions
- the close-on-exec flag for any open file descriptors
- environment
- attached shared memory segments
- resource limits
The differences between the parent and child are
- the return value from
fork
- the process IDs are different
- the two processes have different parent process IDs—the parent process ID of the child is the parent; the parent process ID of the parent doesn't change
- the child's values for
tms_utime
,tms_stime
,tms_cutime
, andtms_ustime
are set to 0- file locks set by the parent are not inherited by the child
- pending alarms are cleared for the child
- the set of pending signals for the child is set to the empty set