簡體   English   中英

退出程序后,在C中的while循環中產生分叉炸彈

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM