簡體   English   中英

分叉過程並等待孩子退出

[英]forking a process and waiting for child to exit

Iam使用C語言進行編程,並試圖學習分叉過程的概念,但是bt iam與以下程序的輸出相混淆。 因此,我需要對此進行一些解釋。

        int main() {
            pid_t pid;
 24         int status, died;
 25         switch(pid = fork()){
 26                 case -1: printf("Can't fork\n");
 27                          exit(-1);
 28                 
 29                 case 0 : printf(" Child is sleeping ...\n"); 
 30                          sleep(5); // this is the code the child runs
 31                          //exit(3); 
 32                          
 33                 default:
 34                          printf("Process : parent is waiting for child to exit\n");
 35                          died = wait(&status); // this is the code the parent runs 
 36                          printf("Child's process table cleared...\n");
 37         }
 38         return 0;
 39 }

The output of the above program is :

Process : parent is waiting for child to exit
Child is sleeping ...
Process : parent is waiting for child to exit
Child's process table cleared...
Child's process table cleared...

這里我不明白為什么這個“孩子的過程表已清除...”要兩次出現。 請解釋。

平台:Linux,gcc編譯器

子項的case語句沒有break ,因此子項也執行default語句

您似乎已經注釋了exit(3) 如果在那里,那就更好了。

我得到了我所缺少的...這是因為那里沒有break語句。如果我將使用break或exit(),輸出將不會像這樣。 謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM