c - 如何将信号传递给子进程

标签 c shell io

标题可能有点令人困惑,所以让我解释一下。我正在尝试编写一个简单的 shell 来练习我的编程。我已经得到一个命令,fork,exec 循环工作。但是,当我在子进程仍在执行时按 CTRL-C 时,我的 shell 将终止,而不是子进程(但子进程将继续运行)。主要功能如下:

int main()
{
    dynarray *args; /* pointer to a dynamic array */
    int bytes_read;
    size_t nbytes = 0;
    char *command;
    pid_t pid;
    printf("Enter command: ");
    while ((bytes_read = getline(&command, &nbytes, stdin)) != -1) {
        if (bytes_read == -1) {
            perror("getline");
            exit(EXIT_FAILURE);
        }
        pid = fork();
        if (pid == -1) {
            perror("fork");
            exit(EXIT_FAILURE);
        }
        else if (pid == 0) { /* child process */
            args = newdynarray();
            char *arg = strtok(command, " \n");
            while (arg != NULL) {
                addstring(args, arg);
                arg = strtok(NULL, " \n");
            }
            if (args->nval == 0) {
                freedynarray(args);
                continue;
            }

            addstring(args, NULL);
            char *fullpath = find_executable(args->strings[0]);
            if (fullpath == NULL) {
                fprintf(stderr, "Couldn't find executable: %s\n", command);
                exit(EXIT_FAILURE);
            }
            if (execv(fullpath, args->strings) == -1) {
                perror("execv");
                exit(EXIT_FAILURE);
            }
        } else {
            int status;
            waitpid(pid, &status, 0);
        }
        printf("Enter command: ");
    } 
    return 0;
}

我没有包含其他部分,因为我认为它们不相关。如何让我的子进程捕获来自 stdin 的所有输入直到它终止?

最佳答案

您可以在父进程中为 SIGINT 注册一个信号处理程序,并在其中使用 kill(2) 向子进程发送信号,您应该指定其 PID存储在某个地方。

关于c - 如何将信号传递给子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10672829/

相关文章:

python - 从python在windows上找到bash可执行文件的位置

linux - Shell脚本参数解析

c++ - 为什么我没有得到正确的输出?

java - 在Java中读取图像文件

file - Groovy 重命名文件

c - 为什么人们将自己的文件夹添加到标准包含路径?

调用 printf ("%d") 两次,const 结果

c - gcc 内联汇编 - `add' 的操作数类型不匹配,试图创建无分支代码

shell - 如何在第 2 列上换行文本

c - 从 uint16_t 读取标志