2013-04-24 43 views
0

我被問及這個問題的作業,並且無法找出答案。如果任何人都可以幫助我,我會非常感激。在C中使用fork()?

什麼Linux庫函數就像一個fork(),但父進程終止?

+1

有沒有AFAIK,雖然也許仰視'exec'將是有益的,因爲它是結合經常使用'叉'(例如[「fork-exec」](http://en.wikipedia.org/wiki/Fork-exec))。 – user2246674 2013-04-24 02:10:31

回答

2

我相當肯定,無論誰賦予你這個功課尋找exec()家庭的功能,從POSIX API頭<unistd.h>,因爲沒有別的更類似於排序的功能,你描述。

exec()函數族執行一個新進程,並用新執行的進程替換當前正在運行的進程地址空間。

man page

的EXEC()函數系列有 一個新的進程圖像替換當前的進程圖像。

它與「終止」父進程不完全相同,但實際上它導致父進程地址空間被子進程的地址空間擦除(替換)的類似情況。

+0

所以你說exec是庫函數? – 2013-04-24 02:11:53

+0

非常感謝你,這很有道理我非常感謝你的幫助。 – 2013-04-24 02:15:52

0

什麼Linux庫函數就像fork(),但父進程 終止?

父進程不應該終止,因爲它必須等待子進程完成執行,之後它們將處於一個稱爲「殭屍狀態」的狀態,現在清理它是父級的責任孩子過程的剩菜。父進程可以在不清理子進程的情況下終止,但是,這不是一個正確的方法,因爲子進程的退出狀態應該由父進程收集和檢查。

下面是一個例子,來證明,我剛纔說的...

#include<stdio.h> 
#include<unistd.h> 
#include<sys/wait.h> 

int main() 
{ 
    pid_t cpid = 1 ; 
    int status; 

    cpid = fork(); 

    // Load a application to the child using execl() , and finish the job 

    printf("Parent waiting for child to terminate\n"); 

    int wait_stat = waitpid(-1,&status,0);  // Parent will hang here till all child processes finish executing.. 
    if (wait_stat < 0) 
    { 
    perror("waitpid error"); 
    exit(-1); 
    } 

    // WIFEXITED and WEXITSTATUS are macros to get exit status information, of the child process 

    if (WIFEXITED (status))   
    { 
    printf("Child of id %u cleaned up\n",wait_stat); 
    printf("Exit status of application = %u\n",WEXITSTATUS(status)); 
    } 

} 
+0

父進程可以終止,在這種情況下,對子進程使用'init'' wait()'。 – 2013-04-24 02:39:08

+0

@JorgeIsraelPeña,是真的,但最好由父母完成,在那裏可以解釋孩子的退出代碼並採取適當的措施 – 2013-04-24 02:40:58

+0

當然,我只是說父母的確可以終止而不用等待兒童;這不一定是一個壞習慣。在某些情況下,父母可能完全不關心孩子的狀況。實際上,一種策略包括分叉兩次並終止第一個子進程,以便原始進程可以繼續處理,而不必關心剩餘(第二個)子進程的狀態(因爲它將由'init'處理)。 – 2013-04-24 02:48:12