gpt4 book ai didi

c - C 中 while 循环中的 Fork 炸弹,在退出程序后发生

转载 作者:行者123 更新时间:2023-11-30 15:28:21 26 4
gpt4 key购买 nike

`#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv){
int pid = 0;
int forever;
static char s; //Uses simply s in the while loop, press s once for each process to
//terminate each process
//char *s; This can't work because it always points to the start of a char array.
//I don't know why. int * doesn't do that.
pid = fork();
if(pid>0)// a child cannot see it's own process ID so pid would be 0 if it was the
child
printf("This is the parent.\n");
else if(pid == 0) printf("This is the child.\n");
while(s != 's'){//One quote is a character, two quotes is a char array
forever = fork();
if(forever>0)
printf("Parent process\n");
else printf("Child process\n");
s = getchar();//I tried making this *s but it causes a segmentation fault
}
return 0;
}`

这导致了一个问题。当我从终端执行程序时,我可以通过为每个进程输入一次“s”来退出程序,然后终端恢复正常。或者看起来是这样。当我在终端按下“向上”箭头时,我进入无限循环并得到 fork 炸弹。我该如何避免这种情况?

最佳答案

更改s

int s = 0;

因为getchar返回 int 并且你确实需要它。使其静态也没有意义(这里也没有坏处,只是糟糕/不寻常的风格)。请注意,您现在需要初始化,这与静态时不同。

然后检查getchar错误/EOF 的返回值,<0并就此终止。这应该可以修复 fork 炸弹,因为它很可能是由 getchar 引起的开始立即返回错误。添加打印以查看发生了什么,特别是打印错误消息或 EOF 状态。

您还应该检查 fork以防万一,也返回错误值。

关于c - C 中 while 循环中的 Fork 炸弹,在退出程序后发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26639600/

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