天天看点

fork 与 vfork 区别的探讨

以下均英文部分取自《Advanced Programing in the UNIX Environment》,中文部分是我的翻译

The function vfork has the same calling sequence and same return values as fork.but the semantic of the two functions differ.

vfork函数和fork函数有相同的调用顺序和相同的返回值。但是二者还是有两点不同。

1.The vfork function is intended to creat a new process when the purpose of the new process is to exec a new program.

  vfork函数意图创建一个希望立刻执行exec函数的新进程.

  the vfork function creat a new process ,just like fork,without copying the address space of the parent into child,as the child won't

reference that address space;the child simply calls exc or exit after the vfork.

  vfork函数创建一个新的进程,就和fork一样,不拷贝父进程的地址空间;这是由于子进程不会引用父进程的地址空间;子进程只是简单的在vfork函数之后调用exec 或者 exit函数

2.Another difference between two functions is that vfork guarantee that the child runs first,until the child calls exec or exit.

When the child calls either of these functions,the parent resume.

  另一个不同是:vfork确保子进程先被执行,一直到子进程调用exec或者exit其中之一市,父进程才被唤醒。

百度上的vfork 和 fork区别的解释,而且这样解释的人相当多:

fork与vfork的区别

1.vfork保证子进程先运行,在它调用exec或exit之后父进程才可能被调度运行。如果在调用这两个函数之前子进程依赖于父进程的进一步动作,则会导致死锁。

2.fork要拷贝父进程的进程环境;而vfork则不需要完全拷贝父进程的进程环境,在子进程没有调用exec和exit之前,子进程与父进程共享进程环境,相当于线程的概念,此时父进程阻塞等待。

    这里,第一点是没有问题的,第二点是值得商榷的。因为我在《Advanced Programing in the UNIX Environment》这本书中看到的内容与这里的说法不符合,

在这本书第二版,8.3节 fork Function中:

    Current implementations don't perform a complete copy of the parent's data,stack,and heap,since a fork is often follwed by exec.instead,a 

technique called copy-on-write (COW)is used.These regions are shared by parent and child and have their protection changed by kernel to read-only.

    目前的实现不执行对父进程data,stack,heap的完整拷贝,因为一般exec会跟在fork函数后。取而代之的是,一种叫做copy-on-write的技术,这些区域(data,stack,heap)是子进程与父进程共享,并且他们的保护被内核改变为只读。

   也就是说第二点目前已经过时了,不使用了,fork函数也不不执行对父进程data,stack,heap的完整拷贝,这些区域(data,stack,heap)是子进程与父进程共享。