gpt4 book ai didi

c - fork() 的行为在此示例中不明确

转载 作者:行者123 更新时间:2023-12-04 06:36:06 24 4
gpt4 key购买 nike

#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?然后为什么最后又出现默认值?

最佳答案

这与 fork 关系不大,而与您的 switch 语句有很大关系。

您的子进程从 fork 返回一个 0 返回码,因此它进入 case 0。不幸的是,由于在 case 0 末尾没有 break 语句,因此它会继续执行到 default。这是因为 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.
}

关于c - fork() 的行为在此示例中不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21130700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com