【发布时间】:2019-08-12 20:30:52
【问题描述】:
我正在为 c 开发一个 shell 程序,并试图弄清楚为什么它在提示用户响应后不断跳出循环。它正确运行命令,但是由于某种原因它中断了。我不知道为什么,我认为这与我做管道的方式有关。
这是我的示例,它应该运行管道命令,并要求用户一次又一次地继续运行该命令,直到用户输入“yes”以外的其他内容。可能是导致中断的 execvp 吗?我怎么能有它,所以它继续循环?使用分叉更新进行编辑。
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
int main()
{
char str[3];
do{
char* leftSide[] = {"ls", NULL};
char* rightSide[] = {"wc", NULL};
pid_t id, id2;
int pipe_fd[2];
pipe(pipe_fd);
id = fork();
if(id == 0){
dup2(pipe_fd[0],0);
close(pipe_fd[1]);
close(pipe_fd[0]);
if(execvp(rightSide[0], rightSide) == -1){
perror("error running pipe right command");
}
}
else{
id2 = fork();
if(id2 == 0){
dup2(pipe_fd[1],1);
close(pipe_fd[1]);
close(pipe_fd[0]);
if(execvp(leftSide[0],leftSide) == -1){
perror("error running pipe left command");
}
}
else{
wait(NULL);
wait(NULL);
}
}
printf("Continue?");
fgets(str, 3, stdin);
str[3] = '\0';
}while(strcmp(str, "yes") == 0);
return 0;
}
【问题讨论】: