开发者

what happens at the lower levels after a fork system call?

开发者 https://www.devze.com 2022-12-19 10:55 出处:网络
I know what the fork() does at the higher level. What I\'d like to know is this - As soon as there is a fork call, a trap instruction follows and control jumps to execute the fork \"handler\" . Now

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 retu开发者_运维问答rn 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 ?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消