繁体   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