天天看點

【OS學習】之 Process API

  UNIX presents one of the most intriguing ways to create a new process with a pair of system calls: fork() and exec(). A third routine, wait(), can be used by a process wishing to wait for a process it has created to complete.

一、The fork() System Call

【OS學習】之 Process API
【OS學習】之 Process API
  The process calls the fork() system call, which the OS provides as a way to create a new process. The odd part: the process that is created is an (almost) exact copy of the calling process.

  有的UNIX系統有兩種形式的fork(), ①複制所有線程,②隻複制調用了系統調用fork()的線程。

Notice:父程序列印了”hello world”,而子程序沒,且子程序被建立後在父程序執行完指令(不包括done指令,即return)後再執行,并從建立它的位置開始。凡凡認為:因為Scheduler(排程程式),将子程序放入就緒隊列。

二、The wait() System Call

【OS學習】之 Process API
【OS學習】之 Process API
  However, if the parent does happen to run first, it will immediately call wait(); this system call won’t return until the child has run and exited2. Thus, even when the parent runs first, it politely waits for the child to finish running, then wait() returns, and then the parent prints its message.

如果在子程序運作時(父程序)沒有什麼可做,那麼它采用系統調用wait()把自己移除就緒隊列來等待子程序的終止

三、The exec() System Call

【OS學習】之 Process API
【OS學習】之 Process API

  調用fork()之後立即調用exec(),那麼沒有必要複制所有線程,因為exec()參數所指定的程式會替代整個程序。

Tips:

int rc = fork();      

對于新(子)程序,系統調用fork()的傳回值為0;而對于父程序,傳回值為子程序的程序辨別符(非零);

繼續閱讀