vfork()的與exit()問題

2009-04-06 9:20 am
照理來說 vfork()的child會與parent使用同一記憶體空間
所以child process應該要使用 _exit(0) 離開
而非使用exit(0)或return

下面的main程式碼片段
在程式碼1
結果理論上應該是在child process呼叫exit(0);後
parent process就沒有機會執行
但是卻印出Parent

程式碼2
符合預期

程式碼3
理論上應該跟exit(0);一樣
parent process沒有機會執行
但是卻印出Parent
而且還出現程式記憶體區段錯誤 (core dumped)

怎麼會這樣?

--------------程式碼1-----------------
pid = vfork() ;
if (pid ==0 )
{
printf("child\n");
exit(0);
}
else
{
printf("Parent\n");
}

結果:
child
Parent

--------------程式碼2-----------------
pid = vfork() ;
if (pid ==0 )
{
printf("child\n");
_exit(0);
}
else
{
printf("Parent\n");
}

結果:
child
Parent



--------------程式碼3-----------------
pid = vfork() ;
if (pid ==0 )
{
printf("child\n");
return 0;
}
else
{
printf("Parent\n");
}

結果:
child
Parent
程式記憶體區段錯誤 (core dumped)
更新1:

我是在Ubuntu寫的程式

更新2:

在使用vfork時 parent process會停止執行 直到child process結束後才執行 那麼這樣的話要如何達到concurrent? 比如我有一個socket的程式 server端要有一個parent process在那listen 然後當accept時則需要使用vfork(假設沒有fork可以用)產生另一新 child process 那parent process這時候就暫停了 這段期間就無法accept新的connection

更新3:

另外一個問題,vfork的parent 和child 都使用同一況address space 那vfork的效果是否跟等價於pthread?

回答 (1)

2009-04-06 2:29 pm
✔ 最佳答案
vfork() is created originally for a short and fast version of fork(). It has the assumption of performing an exec() type system call afterward. If you try to vfork() without any exec(), the consequences are undefined. If your operating system support such a call by itself, it may be just an operating system's choice to support it.

It is possible that your OS environment is multi-threaded and thus, vfork() may inherent part of the threads (one or some) and may cause race condition (this is what one of your code is experiencing).

Modifing parent's code from a child using vfork() will usually cause undefine behavior (so far all OSes that I know say so).

Also, more recent OS kernels will not allow self-modifing codes (no more viruses). This include windows XP SP2 or high. All other major Unix/Linux machine will not support that.

The following document from Solaris/Sun describes this system call nicely:
http://docs.sun.com/app/docs/doc/816-5167/vfork-2?a=view




收錄日期: 2021-04-30 12:58:57
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090406000010KK00708

檢視 Wayback Machine 備份