A new process is created because an existing process makes an exact copy of itself. This child process has the same environment as its parent, only the process ID number is different. This procedure is called forking.
After the forking process, the address space of the child process is overwritten with the new process data. This is done through an exec call to the system.
The fork-and-exec mechanism thus switches an old command with a new, while the environment in which the new program is executed remains the same, including configuration of input and output devices, environment variables and priority. This mechanism is used to create all UNIX processes, so it also applies to the Linux operating system. Even the first process, init, with process ID 1, is forked during the boot procedure in the so-called bootstrapping procedure.
This scheme illustrates the fork-and-exec mechanism. The process ID changes after the fork procedure:
-
parent : read command ---->fork()---> wait(childreturnvalue) ---> receive child status
child: -------> execvp () ---- exit (return)
[root@ipc4 uulp]# pstree -aG
init
├─acpid
├─atd
├─crond
├─cups-config-dae
├─cupsd
├─dbus-daemon-1 --system
├─(events/0)
│ ├─(aio/0)
│ ├─(aio/1)
│ ├─(kacpid)
│ ├─(kblockd/0)
│ ├─(kblockd/1)
│ ├─(khelper)
│ ├─(pdflush)
│ └─(pdflush)
├─(events/1)
│ ├─(kmirrord/0)
│ └─(kmirrord/1)
├─gdm-binary -nodaemon
├─gpm -m /dev/input/mice -t imps2
├─hald
├─irqbalance
├─(khubd)
├─(kjournald)
├─(kjournald)
├─klogd -x
├─(kseriod)
├─(ksoftirqd/0)
├─(ksoftirqd/1)
├─(kswapd0)
├─(lockd)
├─(migration/0)
├─(migration/1)
├─mingetty tty1
├─mingetty tty2
├─mingetty tty3
├─mingetty tty4
├─mingetty tty5
├─mingetty tty6
├─mysqld_safe /usr/bin/mysqld_safe --datadir=/var/lib/mysql...
│ └─mysqld --basedir=/ --datadir=/var/lib/mysql ...
├─named -u named -t /var/named/chroot
├─(nfsd)
├─(nfsd)
├─(nfsd)
├─(nfsd)
├─(nfsd)
├─(nfsd)
├─(nfsd)
├─(nfsd)
├─ntpd -u ntp:ntp -p /var/run/ntpd.pid -g
├─portmap
├─rpc.idmapd
├─rpc.mountd
├─rpc.rquotad
├─rpc.statd
├─rpc.yppasswdd
├─(rpciod)
├─(scsi_eh_0)
├─sendmail
├─sendmail
├─sshd
│ └─sshd
│ └─sshd
│ └─bash
│ └─sesh /bin/su -
│ └─su -
│ └─bash
│ ├─fork2
│ │ ├─fork2
│ │ │ ├─fork2
│ │ │ │ └─+
│ │ │ └─fork2
│ │ ├─fork2
│ │ │ └─fork2
│ │ └─fork2
│ └─pstree -aG
├─syslogd -m 0
├─udevd
├─vmware-guestd --background /var/run/vmware-guestd.pid
├─xfs -droppriv -daemon
├─xinetd -stayalive -pidfile /var/run/xinetd.pid
├─ypbind
└─ypserv