Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 管道命令调用信号函数两次_C++_Shell_Pipe_Signals - Fatal编程技术网

C++ 管道命令调用信号函数两次

C++ 管道命令调用信号函数两次,c++,shell,pipe,signals,C++,Shell,Pipe,Signals,我试图创建一个支持管道的基本外壳。因此,我编写了以下代码: int file_descriptor[2]; if (pipe(file_descriptor) == -1) { perror("error: pipe failed"); return; } int command_pid1 = fork(); if (command_pid1 < 0) { perror("error: fork failed"); return; } if (comma

我试图创建一个支持管道的基本外壳。因此,我编写了以下代码:

int file_descriptor[2];
if (pipe(file_descriptor) == -1) {
    perror("error: pipe failed");
    return;
}

int command_pid1 = fork();
if (command_pid1 < 0) {
    perror("error: fork failed");
    return;
}

if (command_pid1 > 0) {
    // Parent process
    if (waitpid(command_pid1, NULL, 0) < 0) {
        perror("error: waitpid failed");
    }

    int command_pid2 = fork();
    if (command_pid2 < 0) {
        perror("error: fork failed");
        return;
    }

    if (command_pid2 > 0) {
        // Parent process
        close(file_descriptor[0]);
        close(file_descriptor[1]);
        waitpid(command_pid2 , NULL, 0);
        return;
    }

    if (command_pid2 == 0) {
        // Child process
        dup2(file_descriptor[0],STDIN_FILENO);
        close(file_descriptor[0]);
        close(file_descriptor[1]);
        instance.execute(second_command);
        exit(0);
    }
}

if (command_pid1 == 0) {
    // Child process
    if (pipe_err) {
        dup2(file_descriptor[1], STDERR_FILENO);
    } else {
        dup2(file_descriptor[1], STDOUT_FILENO);
    }

    close(file_descriptor[0]);
    close(file_descriptor[1]);
    instance.execute(first_command);
    exit(0);
}
ctrlCHandler
中,我打印用户单击了
Ctrl+C


因此,当我在运行
sleep 1 | sleep 10
时使用
Ctrl+C
时,它会打印
按Ctrl+C
两次,并且只打印一次。我似乎无法找到修复它的方法,所以它只能打印一次。我应该如何处理信号?

此问题中显示的代码不符合stackoverflow.com对a的要求,因此这里的任何人都不可能最终回答此问题;但最多只能猜测。必须对该问题进行编辑,以显示一个最小的示例,不超过一页或两页的代码(“最小”部分),其他人可以完全按照所示剪切/粘贴、编译、运行和复制所描述的问题(“可复制”部分)(这包括任何辅助信息,如程序输入)。有关更多信息,请参阅。“当我在运行
sleep 1 | sleep 10
时使用
Ctrl+C
”——哪个命令处于活动状态是否重要?也就是说,在第一秒钟(第一个命令)中使用
Ctrl+C
是否与在最后十秒钟(第二个命令)中使用的结果相同?当您点击Ctrl+C时,前台进程组中的所有进程都会收到
SIGINT
。此问题中显示的代码不符合stackoverflow.com对,正因为如此,这里的任何人都不可能最终回答这个问题;但最多只能猜测。必须对该问题进行编辑,以显示一个最小的示例,不超过一页或两页的代码(“最小”部分),其他人可以完全按照所示剪切/粘贴、编译、运行和复制所描述的问题(“可复制”部分)(这包括任何辅助信息,如程序输入)。有关更多信息,请参阅。“当我在运行
sleep 1 | sleep 10
时使用
Ctrl+C
”——哪个命令处于活动状态是否重要?也就是说,在第一秒钟(第一个命令)中使用
Ctrl+C
是否与在最后十秒钟(第二个命令)中使用的结果相同?当您点击Ctrl+C时,前台进程组中的所有进程都会收到
SIGINT
signal(SIGINT, ctrlCHandler);