![](/img/trans.png)
[英]Why does program crash after exiting do-while loop asking for input in C?
[英]Fork bomb in a while loop in C, that occurs after exiting a program
`#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來退出程序,終端會恢復正常。 如此看來。 當我在終端機中按“向上”箭頭時,我陷入無盡的循環,並得到了一個叉子炸彈。 如何避免這種情況?
更改s
到
int s = 0;
因為getchar
返回int並且您確實需要它。 也沒有必要將其設置為靜態(這里沒有任何危害,只是不好/不尋常的樣式)。 請注意,您現在需要初始化,而不是靜態的。
然后檢查getchar
返回值的錯誤/ EOF, <0
並以此終止。 那應該修復前叉炸彈,因為它最有可能是由於getchar
開始立即返回錯誤而引起的。 添加打印以查看正在發生的情況,尤其是打印錯誤消息或EOF狀態。
同樣,為了以防萬一,您還應該檢查fork
返回值是否有錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.