对在 shell 中实现多管道感到困惑
所以我一直在尝试在自己的shell程序中实现管道,以便我能够真正理解UNIX在做什么。我现在非常接近,但由于某种原因,当我使用管道时,我的程序会进入无限循环。我很确定我的问题源于我的 waitpid 参数永远不会让最后一个管道关闭,因为如果我在下面的代码中进行最后一个循环,则 i 小于 count-1 而不是 i 小于 count 它将运行管道左侧的命令。但是一旦我把它放回 i 小于 count 它就会永远循环。
if(pipes)
{
for (i=0;i<count-1;i++)
{
if( pipe(fd) ==-1)
{
perror("Pipe failure");
return;
}
read[i+1] = fd[0];
write[i] = fd[1];
}
}
for(i=0;i<count;i++)
{
pid = fork();
if(pid < 0)
{printf("fork failed");}
else if(pid>0)
{pids[i] = pid;}
else
{
if(write[i] != -1)
{
if(dup2(write[i],STDOUT_FILENO) ==-1)
{
perror("dup2 failure");
exit(1);
}
}
if(read[i] !=-1)
{
if (dup2(read[i], STDIN_FILENO)==-1)
{
perror("dup2 failure");
exit(1);
}
}
for (j=0; j<count; j++)
{
close(write[j]);
close(read[j]);
}
execvp(input[i], input);
exit(1);
}//end else
}//end for
for(i=0; i < count; i++){
if(write[i] != -1)
close(write[i]);
if( read[i] != -1)
close (read [i]);
waitpid(pids[i], &status,0);
}
}
return (status);}
我认为我真的非常接近解决方案,但目前我陷入困境。我对管道进行了大量研究,但我想我只是不太明白。感谢您的任何帮助。
So I have been trying to implement piping in my own shell program so that I can actually understand what UNIX is doing. I'm very very close at the moment, but for some reason my program is going into an infinite loop when I pipe. I'm pretty sure my problem is stemming from my waitpid arguments not ever letting the last pipe close, because if I make the final loop in the code below be i is less than count-1 instead of i is less than count it will run the command on the left of the pipe. But once I put it back to i is less than count it just loops forever.
if(pipes)
{
for (i=0;i<count-1;i++)
{
if( pipe(fd) ==-1)
{
perror("Pipe failure");
return;
}
read[i+1] = fd[0];
write[i] = fd[1];
}
}
for(i=0;i<count;i++)
{
pid = fork();
if(pid < 0)
{printf("fork failed");}
else if(pid>0)
{pids[i] = pid;}
else
{
if(write[i] != -1)
{
if(dup2(write[i],STDOUT_FILENO) ==-1)
{
perror("dup2 failure");
exit(1);
}
}
if(read[i] !=-1)
{
if (dup2(read[i], STDIN_FILENO)==-1)
{
perror("dup2 failure");
exit(1);
}
}
for (j=0; j<count; j++)
{
close(write[j]);
close(read[j]);
}
execvp(input[i], input);
exit(1);
}//end else
}//end for
for(i=0; i < count; i++){
if(write[i] != -1)
close(write[i]);
if( read[i] != -1)
close (read [i]);
waitpid(pids[i], &status,0);
}
}
return (status);}
I think I'm really really close to the solution but for the time being I'm stuck. I've researched piping a ton, but I guess I'm just not quite getting it. Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请格式化您的代码。现在是无法读取的。
话虽这么说,但有一些错误:
write[0]
。您正在设置write[count-1]
和read[count]
。pids[i]
,而父级仍打开read[i]
。如果input[i]
想要在标准输入上获得 EOF 之前不会退出,那么它永远不会发生。Please format your code. It is unreadable right now.
That being said, a few errors:
write[0]
. You are settingwrite[count-1]
andread[count]
.pids[i]
while the parent still hasread[i]
open. Ifinput[i]
wants will not exit until it gets EOF on stdin, it will never happen.