home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 38.1 What's in This Chapter Chapter 38
Starting, Stopping, and Killing Processes
Next: 38.3 Managing Processes: Overall Concepts

38.2 fork and exec

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 exec ing 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 ( 1.33 ) 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 exec s the login command. login prompts for a password (if the account has one) and, if the password is okay, exec s the login shell. Whenever you start another program, the shell fork s itself, and the copy exec s whatever program you asked to run.

That's why some commands are built-in to the shell ( 1.10 ) . There's overhead involved in starting a new process. What's more, because a child process can't affect its parent's environment ( 38.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 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.


Previous: 38.1 What's in This Chapter UNIX Power Tools Next: 38.3 Managing Processes: Overall Concepts
38.1 What's in This Chapter Book Index 38.3 Managing Processes: Overall Concepts

The UNIX CD Bookshelf Navigation The UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System