可以成功捕获 CTRL-Z,但不能捕获 SIGTSTP

标签 c shell unix signals

我用 C 编写了一个 shell,它确实具有一些基本功能。我在我的程序中实现了“仅前景模式”,该模式通过 SIGTSTPCTRL-Z 进行切换。但是,我能够捕获 CTRL-Z 信号,但不能捕获 SIGTSTP 信号。这怎么可能? CTRL-ZSIGTSTP 不是一回事吗?不应该让一个人陷入困境吗?

我捕获了信号(我意识到 signal() 已被弃用,但我也尝试了 sigaction(),但问题仍然存在。):

signal(SIGTSTP, trapTstp);

并用这个函数处理它:

void trapTstp() {
    if(foregroundMode == 0) {
        write(1, "Entering foreground-only mode (& is now ignored)\n", 49);
        write(1, ": ", 2);
        fflush(stdout);
        foregroundMode = 1;
    } else {
        write(1, "Exiting foreground-only mode\n", 29);
        write(1, ": ", 2);
        fflush(stdout);
        foregroundMode = 0;
    }
}

如果我运行我的程序并按下 CTRL-Z,我可以成功地进入和退出仅前台模式。但是,我无法捕获 SIGTSTP。例如,如果我运行 sleep 100,获取它的 PID,然后运行 ​​kill -SIGTSTP sleep_pidsleep 100 进程会提前终止输出 Terminated: 15 表示它实际上已被杀死,因此 SIGTSTP 信号未被捕获。

这是我的完整 shell 程序:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>

int statusCode;
int foregroundMode = 0;
int bg = 0;
int bgPsArray[20];
int bgPsCount = 0;
int i;
char line[256];

pid_t popBgProcess() {
    int size = sizeof(bgPsArray)/sizeof(bgPsArray[0]);
    if (size > 0) {
      return bgPsArray[size+1];
    } else {
        return 0;
    }
}

void trapInterrupt(int _) {
    int childStatus;
    pid_t child;
    while ((child = popBgProcess())) {
        if(child != getpid()) {
            kill(child, SIGKILL);
            waitpid(child, &childStatus, 0);
        }
    }
}

void trapTstp() {
    if(foregroundMode == 0) {
        write(1, "Entering foreground-only mode (& is now ignored)\n", 49);
        write(1, ": ", 2);
        fflush(stdout);
        foregroundMode = 1;
    } else {
        write(1, "Exiting foreground-only mode\n", 29);
        write(1, ": ", 2);
        fflush(stdout);
        foregroundMode = 0;
    }
}

int getCommand() {
    printf(": ");
    fflush(stdout);
    if(fgets(line, sizeof(line), stdin) != NULL) {
        char *position = strchr(line, '\n');
    *position = '\0'; // Replace '\n' with '\0'
        if(foregroundMode == 1) { // Foreground mode on
            if((position = strchr(line, '&')) != NULL) {
                *position = '\0'; // Replace '&' with '\0'
            }
            bg = 0; // Ignore '&' so do not create background process
        } else { // Foreground mode off
            if((position = strchr(line, '&')) != NULL) {
                *position = '\0'; // Replace '&' with '\0'
                bg = 1; // Is a background process
            } else {
                bg = 0;
            }
        }
  } else { // If input is null
        return 0;
  }
    return 1;
}

void checkProcessCompletion() {
    int status;
    for(i=0; i<bgPsCount; i++) {
        if(waitpid(bgPsArray[i], &status, WNOHANG) > 0) {
            if(WIFEXITED(status)) { // If exit
                printf("Background PID %d is done: exit value %d\n", bgPsArray[i], WEXITSTATUS(status));
                fflush(stdout);
            } else if(WIFSIGNALED(status)) { // If signal
                printf("Background PID %d is done: terminated by signal %d\n", bgPsArray[i], WTERMSIG(status));
                fflush(stdout);
            }
        }
    }
}

int runCommand(int cmd) {
    if(cmd == 0) { // Return if there was no command
        return 0;
    } else if(strcmp(line, "exit") == 0) {
        exit(0);
    } else if(strstr(line, "#")) { // Comment input (do nothing)
    } else if(strcmp(line, "status") == 0) {
        printf("exit value %d\n", statusCode);
        fflush(stdout);
    }
    else if(strncmp("cd", line, strlen("cd")) == 0) {
        if(line[2] == ' ') { // If space after 'cd' expect directory
            char cwd[1024];
            getcwd(cwd, sizeof(cwd));
            char *path = strstr(line, " ");
            if(path) {
                path += 1;
                char *value;
                value = malloc(strlen(path));
                memcpy(value, path, strlen(path));
                *(value + strlen(path)) = 0;
                sprintf(cwd, "%s/%s", cwd, value); // Directory to change to
                free(value);
            }
            chdir(cwd); // cd to new directory
        } else { // cd with no argument
            char *home = getenv("HOME");
            chdir(home); // cd to HOME directory
        }
    }
    else { // System commands
        pid_t pid, ppid;
        int status;
        char *command;
        char *args[256];
        int argCount;
        command = strtok(line, " ");

        // Create args array for execvp
        args[0] = command;
        argCount = 1;
        args[argCount] = strtok(NULL, " ");
        while(args[argCount] != NULL) { // Add arguments to array
            argCount++;
            args[argCount] = strtok(NULL, " ");
        }
        if((pid = fork()) < 0) { // Fork fails
            perror("fork");
            fflush(stdout);
            exit(1);
        }
        if(pid == 0) { // Child process
            for(i=0; i<argCount; i++) {
                if(strcmp(args[i], "<") == 0) { // Redirecting input
                    if(access(args[i+1], R_OK) == -1) { // File is unreadable
                        perror("access");
                        fflush(stdout);
                    } else { // File is readable
                        int file = open(args[i+1], O_RDONLY, 0);
                        dup2(file, STDIN_FILENO);
                        close(file);
                        execvp(command, &command);
                    }
                }
                else if(strcmp(args[i], ">") == 0) { // Redirecting output
                    int file = creat(args[i+1], 7777);
                    dup2(file, STDOUT_FILENO);
                    close(file);
                    execvp(command, args);
                } else { // No redirection
                    execvp(command, args);
                }
            }
            perror("execvp"); // Error for execvp
            exit(1);
        } else { // Parent process
            if (bg == 1) { // Background process
                int status;
                int process;
                printf("Background PID: %d\n", pid);
                fflush(stdout);
                bgPsArray[bgPsCount] = pid; // Add process to background process array
                bgPsCount++;
                process = waitpid(pid, &status, WNOHANG);
            } else { // Foreground process
                int status;
                waitpid(pid, &status, 0); // Wait on the process
                if(WIFEXITED(status)) {
                    statusCode = WEXITSTATUS(status);
                }
            }
        }
    }
    return 1;
}

int main(int argc, char *argv[], char *envp[]) {
    // Creating 'junk' manually is necessary because output redirection is broken,
    // and a large portion of the grading script is depedent upon it's existence.
    FILE *fp = fopen("junk", "ab+");
    const char *text;
    fprintf(fp, "Junk in junkfile\n");
    fclose(fp);
    signal(SIGINT, trapInterrupt);
    signal(SIGTSTP, trapTstp);
    while(1) {
        checkProcessCompletion(); //Check the processes
        int cmd = getCommand(); // Get command from user
        int result = runCommand(cmd);
        if (result == 0) {
            break;
        }
    }
    return 0;
}

最佳答案

首先,您不能为 shell 本身捕获 SIGTSTP(它应该忽略它),而只能为其子级捕获。其次,如果你真的想写一个作业 Controller shell,你需要借助进程组管理子进程并正确设置前台组。编写一个正确运行作业控制的 shell 是一项繁重的任务。阅读关于 shell、组、 session 、终端控制的 POSIX 标准。

关于您当前的问题。如果您的子进程执行 exec,则每个处理的信号都将重置为其默认行为。这是因为 exec 用新代码恢复了旧代码,所以之前设置的处理程序不再可用。现在你必须让 child 在 TSTP 下表现正常,并且让 parent 通过同步调用 wait/waitpid 的异步帮助来跟踪其状态SIGCHLD。当 child 停止或终止时, parent 能够在返回的状态(WIFEXITEDWIFSIGNALEDWIFSTOPPED)中看到它。

关于可以成功捕获 CTRL-Z,但不能捕获 SIGTSTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42449124/

相关文章:

c - 在postgresql中执行系统命令

c - = 中的不兼容指针

c - 在 C 中制作 shell 时遇到问题

linux - 如何正确停止shell脚本?

xcode - 如何在后台在xcode中运行系统命令

linux - 使用 uuencode,如何在发送时重命名附加的文件?

c - 链表稀疏矩阵之间的矩阵乘积

c - 使用 C 语言的套接字编程,使用 select() 函数

不使用移位将数组中的连续字节转换为指针

java - 如何在java中读取在unix中声明的变量