天天看點

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)是子程序與父程序共享。