views:

168

answers:

2

I know what the fork() does at the higher level. What I'd like to know is this -

  1. As soon as there is a fork call, a trap instruction follows and control jumps to execute the fork "handler" . Now,How does this handler , which creates the child process, by duplicating the parent process by creating another address space and process control block , return 2 values, one to each process ?

  2. At what point of execution does the fork return 2 values ?

To put it in short, can anbody please explain the step-by-step events that take place at the lower level after a fork call ?

+1  A: 

It's not so hard right - the kernel half of the fork() syscall can tell the difference between the two processes via the Process Control Block as you mentioned, but you don't even need to do that. So the pseudocode looks like:

int fork()
{
    int orig_pid = getpid();

    int new_pid = kernel_do_fork();     // Now there's two processes

    // Remember, orig_pid is the same in both procs
    if (orig_pid == getpid()) {
        return new_pid;
    }

    // Must be the child
    return 0;
}

Edit: The naive version does just as you describe - it creates a new process context, copies all of the associated thread contexts, copies all of the pages and file mappings, and the new process is put into the "ready to run" list.

I think the part you're getting confused on is, that when these processes resume (i.e. when the parent returns from kernel_do_fork, and the child is scheduled for the first time), it starts in the middle of the function (i.e. executing that first 'if'). It's an exact copy - both processes will execute the 2nd half of the function.

Paul Betts
could u pls tell me what kernel_do_fork() is ? Is it not calling itself recursively ?
Sharat Chandra
Thanks for taking your time to explain Paul .
Sharat Chandra
+1  A: 

The value returned to each process is different. The parent/original thread get's the PID of the child process and the child process get's 0.

The Linux kernel achieves this on x86 by changing the value in the eax register as it copies the current thread in the parent process.

Robert Christie