c - 从 SIGCHLD 返回的信号似乎是错误的

标签 c unix signals child-process

我已经用 C 语言编写了一个基本的 shell,我正在尝试从子进程中捕获 SIGTSTP 信号。为此,我为 SIGCHLD 设置了一个处理程序,但返回的信号编号是 20,而它应该是 24

我有我的 SIGCHLD 处理程序:

signal(SIGCHLD, trapChld);

void trapChld(int signo) {
    printf("%d", signo);
}

这会在 kill -SIGTSTP child_pid 运行时打印信号 20。为什么会发生这种情况?

这是我的完整代码:

#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 trapChld(int signo) {
    printf("%d", signo);
    if(signo == 24) {
        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(SIGCHLD, trapChld);
    while(1) {
        checkProcessCompletion(); //Check the processes
        int cmd = getCommand(); // Get command from user
        int result = runCommand(cmd);
        if (result == 0) {
            break;
        }
    }
    return 0;
}

最佳答案

您没有告诉我们您在哪个平台上运行,所以这只是一个猜测,但也许是因为该平台将 SIGTSTP 定义为 20?

Linux 可以,例如:

$ grep SIGTSTP /usr/include/asm/signal.h
#define SIGTSTP         20

更好的问题是为什么您认为它应该是 24?在 AIX 上是 18。在 HP-UX 上是 25。各种 Cygwin 头文件将其定义为 8、18 或 24(因为 Cygwin 头文件来自 glib,并且充满了特定于平台的条件编译恶作剧); 18 是运行时实际使用的值。

在 Solaris 上,现在恰好是 24。我相信 Solaris 2 从 SVR4 继承了它,并且后​​续的 Solaris 版本保留了它。但是任何适用的规范(SUS 及其祖先,例如 POSIX 和 XPG3)都没有对信号编号进行标准化。

不要假设信号值是固定的。这就是为什么你有 signal.h。

哦,在大多数支持它的平台上,sigaction(2) 比 signal(2) 更可取。

关于c - 从 SIGCHLD 返回的信号似乎是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42470350/

相关文章:

c - C 8位16位32位编译器的区别

c++ - 在 Mac 上使用 C 或 C++ 进行 GUI 编程入门

c - C 中的指针 : Data type or operation

linux - 如何计算具有特定条目的文件数?

c - fork() 怎么可能返回两个值?

c - C语言凯撒密码程序的高级思考

unix - zcat 管道到 grep

c++ - 如何用断言做一些有用的事情?

c - 为什么第二线程中的暂停(2)不返回?

WSGI 上托管的 Python 信号