We've already discussed fork and exec way back in article 1.11, but the concept comes up so often in this chapter that we thought we ought to have a closer cross reference.
Put simply, fork and exec are the UNIX system calls (requests for operating system services) that UNIX programs use to create new processes. When you start up a UNIX system, it starts with only one process, a program called init.
How does init magically turn into the hundreds or perhaps even thousands of processes that make up a working UNIX system? That's where fork and exec come in.
One process spawns another ("spawn" is another term you should get used to seeing) either by replacing itself when it's done - an exec - or if it needs to stay around, by making a copy of itself - a fork. In the latter case, the forked copy commits polite suicide by execing the desired second program.
A good example of this whole sequence can be seen in the way
a UNIX system's login procedure for terminals (non-
The init process spawns a series of getty
processes, each of which monitors a serial port (a tty) looking for
It's the getty program that actually puts up the
Once someone actually types a login name, getty's job is done; it execs the login command. login prompts for a password (if the account has one) and, if the password is okay, execs the login shell. Whenever you start another program, the shell forks itself, and the copy execs whatever program you asked to run.
That's why. There's overhead involved in starting a new process. What's more, because , some commands don't make sense as separate processes. For example, cd must be built in, or it couldn't change the working directory for the current shell.
There's an exec command that you can type at a shell prompt; see article 45.7. Watch out, though, it will replace your shell with whatever command you exec, with no going back. This is useful only if you want to replace your shell with some other interactive command interpreter with similar powers (as in article 22.22), or if you'll be ready to log out when the command you exec finishes.