fork() 怎么可能返回两个值?
既然 C 中的函数始终只返回一个值,那么同样是函数的 fork()
怎么会返回两个值呢?
Since a function in C returns only one value, all the time, how can fork()
, which is also a function, return two values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
fork 函数向创建的子进程返回 0,并向父进程返回子进程的 ID。
这两个单独的进程各自返回一个值。
因此,可以将其更多地视为在每个
线程进程上调用一个返回。The fork function returns 0 to the child process that was created and returns the childs ID to the parent process.
The two seperate processes are each returned a single value.
So think of it more as one return being called on each
threadprocess.正如 Gnostus 所说,fork() 函数不会返回两个值。
它的作用是返回一个值,就像所有函数一样,但它返回两次。
一次在父进程中,一次在子进程中。父进程获取返回给它的子进程 ID,子进程获取 0 - 无效的进程 ID,因此代码可以判断它是子进程。
子进程是一个新进程,运行相同的代码,并且与生成它的父进程位于代码中的相同位置。
As Gnostus says, the fork() function does not return two values.
What it does is return a single value, the way all functions do, but it returns twice.
Once within the parent process and once within the child. The parent process gets the child's process ID returned to it, the child gets 0 - an invalid process ID, so the code can tell it is the child.
The child is a new process, running the same code and is at the same place in the code as the parent that spawned it.
如果您阅读、构建并运行以下程序,您应该更好地了解正在发生的事情。
需要 fflush(stdout) 的原因是,由于该进程是通过 fork 重复的,这意味着 stdio 为 stdout 所做的缓冲也会被重复。第一个打印语句末尾的“\n”可能会使其继续并刷新标准输出,但这并不能保证。
If you read, build, and run the following program you should get a better idea of what is going on.
The reason that the
fflush(stdout)
is needed is that since the process is duplicated by fork that means that the buffering done for stdout by stdio is duplicated as well. The "\n" at the end of that first print statement may make it go ahead and flush stdout, but this isn't guaranteed.这里的关键见解是考虑这样一个事实:在
fork()
之后,您实际上拥有程序的两个副本。这是两个进程,运行相同的代码副本,并且执行指针完全位于同一行代码,即fork()
,准备返回。操作系统安排 fork() 在父进程中返回子进程的 pid,并在子进程中返回零(如果一切顺利的话)。
这就是为什么他们说
fork()
返回两次。每个过程一次。The key insight here is to think about the fact that after a
fork()
you have really two copies of your program. These are two processes, running the same exact copy of your code, and the execution pointer is exactly at the same line of code i.e.fork()
, poised to return.The OS arranges for the
fork()
to return in the parent process with the pid of the child, and for it to return in the child process with zero (if things go well).That is why they say that
fork()
returns twice. Once in each process.fork
不返回两个值。在fork
系统调用之后,您只需让两个独立的进程执行相同的代码,并且从fork
返回的 pid 是区分您所在进程的唯一方法 -父母或孩子。fork
does not return two values. Right after afork
system call you simply have two independent processes executing the same code, and the returned pid fromfork
is the only way to distinguish which process are you in - the parent or the child.