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);