fork()如何为子进程返回 [英] How does fork() return for child process

查看:117
本文介绍了fork()如何为子进程返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道fork()对于子进程和父进程返回的方式有所不同,但是我无法找到有关此情况的信息.子进程如何从fork接收返回值0?在调用堆栈方面有什么区别?据我了解,对于父母来说,是这样的:

I know that fork() returns differently for the child and parent processes, but I'm unable to find information on how this happens. How does the child process receive the return value 0 from fork? And what is the difference in regards to the call stack? As I understand it, for the parent it goes something like this:

父进程-调用fork-> system_call--调用fork-> fork执行-返回-> system_call--返回->父进程.

parent process--invokes fork-->system_call--calls fork-->fork executes--returns to-->system_call--returns to-->parent process.

子进程会发生什么?

推荐答案

%man fork

返回值

Upon successful completion, fork() returns a value of 0 to the child
process and returns the process ID of the child process to the parent
process.  Otherwise, a value of -1 is returned to the parent process, no
child process is created, and the global variable [errno][1] is set to indi-
cate the error.

发生的事情是,在fork系统调用中,整个过程被复制了.然后,每个中的fork调用都会返回.不过,这些现在是不同的上下文,因此它们可以返回不同的返回码.

What happens is that inside the fork system call, the entire process is duplicated. Then, the fork call in each returns. These are different contexts now though, so they can return different return codes.

如果您真的想知道它的工作原理,可以随时检查源文件!如果您不习惯阅读内核代码,则代码会有些混乱,但是内联注释可以很好地提示正在发生的事情.

If you really want to know how it works at a low level, you can always check the source! The code is a bit confusing if you're not used to reading kernel code, but the inline comments give a pretty good hint as to what's going on.

在源代码中最有趣的部分是您的问题的明确答案,这是在fork()定义本身的末尾-

The most interesting part of the source with an explicit answer to your question is at the very end of the fork() definition itself -

if (error == 0) {
    td->td_retval[0] = p2->p_pid;
    td->td_retval[1] = 0;
}

"td"显然拥有不同线程的返回值列表.我不确定该机制是如何工作的(为什么没有两个单独的线程"结构).如果错误(从fork1返回,实数"分叉函数)为0(无错误),则取第一个". (父)线程并将其返回值设置为p2(新进程)的PID.如果是秒",则为秒".线程(在p2中),然后将返回值设置为0.

"td" apparently holds a list of the return values for different threads. I'm not sure exactly how this mechanism works (why there are not two separate "thread" structures). If error (returned from fork1, the "real" forking function) is 0 (no error), then take the "first" (parent) thread and set its return value to p2 (the new process)'s PID. If it's the "second" thread (in p2), then set the return value to 0.

这篇关于fork()如何为子进程返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆