## 24.2. fork and exec

We discuss fork and exec in Section 27.2, 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-network (Section 1.21) logins) works. The init process spawns a series of getty processes, each of which monitors a serial port (a tty), looking for activity. It's the getty program that actually puts up the first `login`: prompt.

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 some commands are built into the shell (Section 1.9). There's overhead involved in starting a new process. What's more, because a child process can't affect its parent's environment (Section 24.3), 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 Section 36.5. 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, or if you'll be ready to log out when the command you exec finishes.

-- TOR

Copyright © 2003 O'Reilly & Associates. All rights reserved.