#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(void)
{
pid_t pid;
switch(pid =fork())
{
case -1:
perror("fork"); /* something went wrong */
exit(1);
/* parent exits */
case 0:
printf(" This is the child process mention in case 0 of switch!, but why case 0 reached?\n");
default:
printf("default case: pid returned by fork is %d\n",pid );
}
return 0;
}
输出
root@heena:/home/heena/fork# ./a.out
default case: pid returned by fork is 4640
root@heena:/home/heena/fork# This is the child process mention in case 0 of switch!, but why case 0 reached?
default case: pid returned by fork is 0
之后我必须按回车才能到达提示。
为什么案例0在案例是默认情况下有效。此外,命令提示如何自动第二次出现并执行案例0?然后为什么默认会再次出现?
答案 0 :(得分:4)
这与fork
几乎没有关系,与您的switch
声明有很大关系。
您的子进程从fork
返回0
返回码,以便进入case 0
。不幸的是,由于您在default
末尾没有break
语句,因此会继续case 0
。这是因为case
末尾的默认行为只是落在下一个case
(如果有的话)。
与以下内容没有什么不同:
int i = 1;
switch (i) {
case 1: puts ("It was one");
case 2: puts ("It was two");
case 3: puts ("It was three");
default: puts ("It was something else");
}
最终会出现看似精神病的输出:
It was one
It was two
It was three
It was something else
要修复它(您的代码,而不是上面的示例),请使用:
switch (pid =fork()) {
case -1:
perror ("fork");
exit (1); // will exit rather than fall through.
case 0:
printf (" This is the child process\n");
break; // will end switch rather than fall through.
default:
printf ("default case: pid returned by fork is %d\n",pid );
// nothing needed here since switch is ending anyway.
}
答案 1 :(得分:3)
您对输出感到困惑:
对于父进程,它转到default
并打印pid,然后退出,因为您不等待孩子完成。然后你会看到命令提示符
你看到了这个:
root @heena:/ home / heena / fork#。/ a.out
默认情况:fork返回的pid是4640
root @heena:/ home / heena / fork#
对于子进程,执行case 0
并打印该行,然后,因为此案例后没有break
语句,它将进入默认情况并且打印此(即子)进程的pid为0,然后退出。
所以你看到这个:
这是切换的情况0中的子进程提及!但是为什么是情况0 达到?
默认情况:fork返回的pid是0
只需在break;
之后插入case 0:
,您的输出就会清晰。
答案 2 :(得分:1)
你错过了0的情况