Next: Executing a File, Previous: Process Identification, Up: Processes
The fork function is the primitive for creating a process.
It is declared in the header file unistd.h.
The
forkfunction creates a new process.If the operation is successful, there are then both parent and child processes and both see
forkreturn, but with different values: it returns a value of0in the child process and returns the child's process ID in the parent process.If process creation failed,
forkreturns a value of-1in the parent process. The followingerrnoerror conditions are defined forfork:
EAGAIN- There aren't enough system resources to create another process, or the user already has too many processes running. This means exceeding the
RLIMIT_NPROCresource limit, which can usually be increased; see Limits on Resources.ENOMEM- The process requires more space than the system can supply.
The specific attributes of the child process that differ from the parent process are:
The
vforkfunction is similar toforkbut on some systems it is more efficient; however, there are restrictions you must follow to use it safely.While
forkmakes a complete copy of the calling process's address space and allows both the parent and child to execute independently,vforkdoes not make this copy. Instead, the child process created withvforkshares its parent's address space until it calls_exitor one of theexecfunctions. In the meantime, the parent process suspends execution.You must be very careful not to allow the child process created with
vforkto modify any global data or even local variables shared with the parent. Furthermore, the child process cannot return from (or do a long jump out of) the function that calledvfork! This would leave the parent process's control information very confused. If in doubt, useforkinstead.Some operating systems don't really implement
vfork. The GNU C library permits you to usevforkon all systems, but actually executesforkifvforkisn't available. If you follow the proper precautions for usingvfork, your program will still work even if the system usesforkinstead.