问题描述
我正在尝试创建自己的“ unix风格” shell。我希望能够使用循环将N条命令管道在一起。但是到目前为止,我一直没有成功。我能够通过管道将2个命令组合在一起,现在我试图通过管道将3个命令组合在一起。当我执行时,什么也没有发生,并且看起来父进程只是在等待子进程。供参考,我尝试执行的命令是:ls |头-3 |尾巴-1。
int p1[2],p2[2]; //pipes
pipe(p1);
int pid1,pid2;
pid1 = fork(); //create child
if (pid1 ==0) { //child
close(1); //close stdout
dup(p1[1]);
close(p1[0]); //closes pipes we dont need
close(p1[1]);
exec(command[0][0],command[0]); //execute command
exit(0);
}
pipe(p2); //create 2nd pipe
pid2=fork(); //create child
if(pid2 == 0) { //child process
close(0); //close stdin
dup(p1[0]);
close(p1[0]); //close pipes we dont need
close(p1[1]);
close(1); //close stdout
dup(p2[1]);
close(p2[0]);
close(p2[1]);
exec(command[1][0],command[0]); //execute command
exit(0);
}
else
{ //parent
wait(NULL); //stops here
wait(NULL); //waiting for child processes to complete
close(p1[0]);
close(p1[1]);
close(0); //close stdin
dup(p2[0]);
close(p2[0]); //close pipes we dont need
close(p2[1]);
exec(command[2][0],command[2]); //execute command
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)