C中的Shell来执行管道
嗨,我的pipeexecute函数有点问题,我希望C中的shell能够执行管道。arg1是管道之前的输入,arg2是管道之后的命令。我希望程序在ctr-d之后终止,但它似乎在没有它的情况下退出,代码执行的那一刻。我输入的一个例子是ls | wc,其中arg1=ls和arg2=wc。非常感谢您的帮助/指点C中的Shell来执行管道,c,C,嗨,我的pipeexecute函数有点问题,我希望C中的shell能够执行管道。arg1是管道之前的输入,arg2是管道之后的命令。我希望程序在ctr-d之后终止,但它似乎在没有它的情况下退出,代码执行的那一刻。我输入的一个例子是ls | wc,其中arg1=ls和arg2=wc。非常感谢您的帮助/指点 int executepipe (char ** arg1, char ** arg2) { int fds[2]; int child=-1; int status =
int executepipe (char ** arg1, char ** arg2) {
int fds[2];
int child=-1;
int status = pipe(fds);
if (status < 0)
{
printf("\npipe error");
return -1;
}
int pid =-1;
pid= fork();
while(1){
if (pid < 0) { //error!
perror("fork");
exit(1);
}
//child
if (pid == 0){// child process (command after the pipe)
//signal(SIGINT, SIG_DFL);
//signal(SIGQUIT, SIG_DFL);
close(fds[1]);//nothing more to be written
dup2(fds[0], 0);
execvp(arg2[0], arg2);
//if errors exist execv wouldn't have been invoked
perror("cannot execute command");
exit(1);
}
else { // parent process (command before the pipe)
close(fds[0]);
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
dup2(fds[1], 1);
close(fds[1]);
execvp(arg1[0], arg1);
//if errors exist execv wouldn't have been invoked
perror("cannot execute command");
exit(1);
}
if ( wait(&child) == -1 ){
perror("wait");}
}
return 0;
};
int executepe(字符**arg1,字符**arg2){
int-fds[2];
int child=-1;
int状态=管道(fds);
如果(状态<0)
{
printf(“\n管道错误”);
返回-1;
}
int-pid=-1;
pid=fork();
而(1){
如果(pid<0){//错误!
佩罗尔(“福克”);
出口(1);
}
//孩子
if(pid==0){//子进程(管道后面的命令)
//信号(SIGINT、SIG_DFL);
//信号(SIGQUIT、SIG_DFL);
close(fds[1]);//没什么要写的了
dup2(fds[0],0);
execvp(arg2[0],arg2);
//如果存在错误,则不会调用execv
perror(“无法执行命令”);
出口(1);
}
else{//父进程(管道前的命令)
关闭(fds[0]);
信号(SIGINT、SIG_DFL);
信号(SIGQUIT、SIG_DFL);
dup2(fds[1],1);
关闭(fds[1]);
execvp(arg1[0],arg1);
//如果存在错误,则不会调用execv
perror(“无法执行命令”);
出口(1);
}
如果(等待(&child)=-1){
佩罗(“等待”);}
}
返回0;
};
如果所有路径都替换了当前进程,为什么会在过程中出现循环以及之后出现代码?调试的第一个技巧:简化!首先,将您的程序简化为没有问题的最简单的示例。然后一次向程序中添加一小段,使用额外的警告进行构建,然后进行测试。如果你收到警告或任何测试失败,那么在继续下一个小程序之前,先修复错误。@Someprogrammerdude“删除东西直到它工作”的方法可以创造奇迹。许多编辑都有一个快速的“注释此块”宏,这使它在实践中变得非常简单。谢谢大家,我来试一试。你们有一个while
循环吗?为什么?但是,fork
在循环之上/之外。管道的调用也是如此。因此,我预计在父循环的第二次迭代中会出现错误(即第二次迭代中的pid
被使用/过时/无效,因为第一次循环迭代中的wait
)。换句话说,管道fds
和pid
在第一次迭代后都无效。