捕获SIGINT和SIGTSTP信号会导致错误。

3
我正在制作一个简单的shell。当用户点击control-Z时,我只想简单地切换到前台模式。当用户点击control-C时,我只想终止前台进程(后台子进程应忽略它)。
如果我运行我的shell并发送像"ls"或"sleep 10"这样的命令,它们都能正常工作。但是在执行完这些命令后,如果我按下control-Ccontrol-Z,这些命令就停止工作了。例如,在control-C之后发送"ls"将不会执行。这是为什么?是信号干扰了标准输入吗? 更新收到的评论 现在使用sigaction,我可以正确处理control-C信号。然而,尝试control-Z会导致一个fork炸弹。我该如何防止这种情况发生?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include <limits.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>

int last_exit_status = 0;
int last_termination = 0;
int backgroundChildrenRunning = 0;
int backgroundPid = 0;
int ignoreBackground = 0;


void child_sigint_handler(int signum) {
    //nothing here for now
}
void child_sigint_handlerSec(int signum) {
    //do nothing here for background process
}

void sigint_handler(int signum) {// Signal handler for SIGINT (Ctrl-C)
   //nothing here now
}

void sigtstp_handler(int signum) {// Signal handler for SIGTSTP
  //nothing here for now
}

void check_background() {
    if (backgroundChildrenRunning > 0) {        //this function is to print the background process termination signal
        int currentStatus;
        int completedChild = waitpid(-1, &currentStatus, WNOHANG);      //use WHOHANG so it does not block

        if (completedChild > 0) {
            if (WIFEXITED(currentStatus)) {
                printf("Background process with ID %d has been completed. Exit value: %d.\n", completedChild, WEXITSTATUS(currentStatus));
                last_termination = WEXITSTATUS(currentStatus);
            }
            else {
                if (completedChild == backgroundPid) {
                    printf("Background process with ID %d has been completed. Terminated by signal: %d.\n", completedChild, WTERMSIG(currentStatus));
                    last_termination = WTERMSIG(currentStatus);
                }
            }
            backgroundPid = 0;
            backgroundChildrenRunning -= 1;
        }
    }
}

char* prompt(int pid);

//main func
int main() {
    int x = 0;
    char *token;
    char *argv[1024]; // Array to store command and arguments
    int i = 0;

    struct sigaction sa;
    sa.sa_flags = SA_RESTART;
    sa.sa_handler = sigint_handler;
    sigaction(SIGINT, &sa, NULL);

    struct sigaction sa_tstp;
    sa_tstp.sa_handler = sigtstp_handler;
    sigaction(SIGTSTP, &sa_tstp, NULL);

    while(x == 0) {
        check_background();
        int pid = getpid();
        char* command = prompt(pid);   //get user input
        if (command != NULL) {

            int childExitMethod;
            pid_t spwanPID = fork();

            token = strtok(command, " "); // Split the command into tokens
            while (token != NULL) {//add in all tokens into arr
                argv[i] = token;
                token = strtok(NULL, " ");
                i++;
            }
            argv[i] = NULL;
            int hasSymbolEnd = 0;
            if (strcmp(argv[i - 1], "&") == 0){     //checks to see if background or foreground process
                if (ignoreBackground == 0) {
                    hasSymbolEnd = 1;
                }
                argv[i - 1] = NULL; // Remove the '&' symbol
            }

            switch (spwanPID){
            case -1:
                last_exit_status = 1;
            case 0:
                if (hasSymbolEnd == 1) {
                    backgroundPid = getpid();
                    sa.sa_handler = child_sigint_handlerSec;
                } else {
                    sa.sa_handler = child_sigint_handler;
                }

                execvp(argv[0], argv);
                last_exit_status = 1;
                exit(1);
                
            default:
                if (hasSymbolEnd == 0){
                    waitpid(spwanPID, &childExitMethod, 0); // Wait for the child only if background
                    if (WIFEXITED(childExitMethod) && !WEXITSTATUS(childExitMethod)) {
                        last_exit_status = 0;
                    } else if (!WIFSIGNALED(childExitMethod)){
                        printf("bash: %s: command not found\n", command);
                        last_exit_status = 1;
                    }

                    if (WIFSIGNALED(childExitMethod)) { //Check if the child was terminated by a signal
                        int terminatedBySignal = WTERMSIG(childExitMethod);
                        printf("Terminated by signal %d\n", terminatedBySignal);
                    }
                } else {
                    printf("background pid is %d\n", spwanPID); 
                    backgroundChildrenRunning += 1;
                }
                
            }
        }
    }
    return 0;
}

char* prompt(int pid) {
    printf("%d:", pid);
    fflush(stdout);

    char* input = NULL;
    size_t input_size = 0;
    ssize_t read_bytes = getline(&input, &input_size, stdin);// Use getline to read user input

    if (read_bytes == -1) {
        free(input); // Free the memory
        return NULL;
    }

    if (input[read_bytes - 1] == '\n') {// Remove the newline character at the end
        input[read_bytes - 1] = '\0';
    }
    return input;
}

5
注意:在信号处理程序中调用 printfexit 是不安全的。请参阅:signal-safety(7) - undefined
1
不要使用signal()来设置信号处理程序,应该使用sigaction()(并注意SA_RESTART标志)。信号处理程序允许访问的唯一类型是sig_atomic_t。在x86上,它是int,但显式类型会更易读。从信号处理程序访问的变量应该是volatile的。在execvp()失败后打印相关错误消息。将命令拆分为标记后,在父进程和子进程中都会执行两次。还有一些其他缺陷...对于交互式应用程序,比如shell,我建议不要搞信号处理程序,而是使用signalfd()来使用事件循环。 - undefined
@dimich 谢谢你的帮助。你能给个使用 signalfd() 的例子吗? - undefined
@dimich 我使用了你的建议,现在Ctrl+C功能完美运行。但是当我尝试使用Ctrl+Z时,会出现一个fork bomb(进程炸弹)的问题。我尝试进行调试,但无法找出原因。我已经更新了我的代码。 - undefined
1
@ahmed 你的代码忽略了 getline() 可能返回 0 的情况。这使得 if (input[read_bytes - 1] == '\n') ... 非常危险,因为它将访问 input 缓冲区之外的内存。请参考 从 fgets() 输入中删除尾随的换行符 - undefined
显示剩余7条评论
1个回答

1
关于SIGINT的处理,你可以:
- 在主shell中忽略SIGINT。 - 在子进程中,只有当它们是前台进程时,才处理SIGINT以终止。
而对于SIGTSTP的处理,可以在sigtstp_handler中实现一个切换前台模式的功能。
// rest of your includes and global variables

void sigint_handler(int signum) {
    // Main shell should ignore SIGINT
}

void sigtstp_handler(int signum) {
    ignoreBackground = !ignoreBackground; // Toggle the state
}

// rest of your functions

int main() {
    // rest of your main function

    struct sigaction sa_ignore;
    sa_ignore.sa_handler = SIG_IGN; // Ignore signal
    sigaction(SIGINT, &sa_ignore, NULL);

    struct sigaction sa_tstp;
    sa_tstp.sa_handler = sigtstp_handler; // Handle SIGTSTP
    sigaction(SIGTSTP, &sa_tstp, NULL);

    // rest of your main function

    switch (spwanPID) {
    // rest of your switch case

    case 0:
        // Child process
        if (hasSymbolEnd == 1) {
            // Background process should ignore SIGINT
            sigaction(SIGINT, &sa_ignore, NULL);
        } else {
            // Foreground process should handle SIGINT
            struct sigaction sa_child;
            sa_child.sa_handler = SIG_DFL; // Default signal handling
            sigaction(SIGINT, &sa_child, NULL);
        }

        execvp(argv0, argv);
        // rest of your case 0
    }
    // rest of your main function
}

你将获得以下内容,用于你的fork process
  User Input
      |
      v
   Shell Loop
      |
      +---> Fork Process
      |        |
      |        +---> Execute Command (ls, sleep)
      |        |         |
      |        |         +---> SIGINT Handling (Child)
      |        |
      |        +---> SIGINT Ignored (Background Child)
      |
      +---> SIGINT Ignored (Main Shell)
      |
      +---> SIGTSTP Toggles Foreground Mode (Main Shell)

每次我点击控制键Z时,仍然会出现fork bomb。然而,控制键C的处理是正确的。
当捕获到SIGTSTP信号时,应该切换到仅前台模式。然而,它不应该创建新的进程或干扰现有的进程管理。
确保主循环在不需要时不会fork新的进程,特别是在处理SIGTSTP信号后。sigtstp_handler应该只切换一个标志(ignoreBackground),而不执行任何进程创建或其他复杂操作。在处理SIGTSTP信号后,验证主循环是否没有fork新的进程。如果程序的状态在捕获信号后没有正确管理,可能会发生这种情况。
我已经添加了一些用于调试的printf语句。
void sigtstp_handler(int signum) {
    ignoreBackground = !ignoreBackground; // Toggle the state
    printf("Toggled foreground-only mode to %d\n", ignoreBackground);
    fflush(stdout);
}

int main() {
    // rest of your main function setup

    while (x == 0) {
        check_background();
        // rest of your command reading and parsing

        if (command != NULL) {
            // tokenizing and processing the command

            if (strcmp(argv[0], "") != 0) { // Check if the command is not empty
                pid_t spwanPID = fork();

                // rest of your fork and exec logic

            } else {
                free(command); // Free the command string if it is empty
            }
        }
    }
    // rest of your main function
}

主要的想法是确保空命令或解析不正确的命令不会导致意外的分叉。

谢谢,每次我点击Ctrl+Z,仍然会出现一个fork bomb。然而,Ctrl+C的处理是正确的。 - undefined
@ahmed 好的,我已经编辑了答案以回应你的评论。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接