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

问题描述 投票:0回答:1

你好,我正在制作一个简单的外壳。当用户单击控件 Z 时,我想简单地切换仅前台模式的状态。当用户单击控件 C 时,我只想终止前台进程(后台子进程应该忽略它)。

如果我运行 shell 并发送“ls”或“sleep 10”等命令,它们就会起作用。这样做后,如果我按控制 C 或 Z,这也有效。只有在发送控制 C 或 Z 后,正常命令才会停止工作。例如,在命令 C 之后发送“ls”将不会执行。为什么是这样?信号与 STDIN 是否混乱?

更新收到的评论

现在使用 sigaction 我可以正确处理命令 C 信号。然而尝试控制 Z 会导致叉子炸弹。我怎样才能防止这种情况发生。

#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;
}
c signals
1个回答
0
投票

关于 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过程

  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)
© www.soinside.com 2019 - 2024. All rights reserved.