0

我正在用 C 语言编程并尝试学习分叉进程的概念,但我对以下程序的输出感到困惑。所以我需要对此进行一些解释。

        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编译器

4

2 回答 2

6

break孩子的语句中没有case,因此孩子也执行该default语句

你似乎已经注释掉了exit(3)。如果它在那里就更好了。

于 2012-05-10T06:37:54.163 回答
0

i got it what i was missing ... it is because of the absence of the break statement there.If i would have used break or exit(), output wouldn't have been like this. Thanks.

于 2012-05-10T06:43:50.197 回答