[lug] Idea for a new tutorial....maybe???

PC Drew drewpc at colorado.edu
Sat Apr 8 20:08:12 MDT 2000


Thus spake John Starkey on Saturday, April 08, 2000, 6:44:42 PM:

JS> And what did you mean by "forking a process". I use 'ps' a lot I know what
JS> a process is and how to determine parent/child and initd, etc. But how is
JS> a process created (ie, the forking)? 

Okay, so you use 'ps' and you understand what a process is.  How does
a process become a process?  If the shell is just a program, and it
runs other programs, then why isn't there just one big process?  The
shell actually 'forks' a process off and then executes that program.

When you type 'ls' into your shell, one of the things that has to
happen is that the shell forks off a process.  What that does is it
copies the entire shell process into a new location in memory, then
continues running _both_ processes.  At this point, you have a parent
and a child process running exactly the same code, doing exactly the
same thing.  Inside the code, an if statement is used to differentiate
between the parent and the child.  The if statement will do one thing
for the child and another for the parent.

The child process will make the exec() function call.  This is the
actual function call that runs the program 'ls'.  What happens, is
the code for ls is loaded into the same chunk of memory that the child
process was in, and the kernel starts the process over again.

The parent, meanwhile, makes the wait() call.  This basically puts the
parent process to sleep until the child process (ls) has completed.
This is why when you execute a program, you can't do anything in your
shell until it completes.  If you type "^Z" then "bg" or put a "&"
after the program name, then it'll go into the background and you
won't "lose" your shell like this.

Here's an example of the fork() and exec() function calls:

if((pid = fork()) >= 0) {
    if(pid == 0) {
        execv(location, argv);  // The child process executes
        "location".
        exit(-1);
    } else {
        wait3(NULL, NULL, &ru_child);  // The parent process waits.
    }
} else {
    cout << "fork failed.\n";
}






More information about the LUG mailing list