[英]piping for a simple shell in c
我正在尝试在我在 C 中编写的一个简单的 shell 程序中实现管道。
但出于某种原因,当我尝试运行ls | wc -l
时,我没有得到 output ls | wc -l
。
我真的不确定为什么会这样,因为我基本上是将子进程的 output 放到pipe[1]
中,它在 pipe 指示符之前执行命令,而我将父进程的输入放到pipe[0]
中,它在 pipe 之后执行命令指示器,它应该打印到终端,因为父级的 output 从未更改过,我现在的方法是如果管道被标记为子级中的呼叫叉并进行管道。
下面的代码
int pipe1[2];
int pipepid;
int piping; /*flag for piping*/
int pipeposition;/*index of pipe indicator*/
//* code... */
if(pipe(pipe1)!= 0){
perror("pipe");
exit(1);
};
/* split commands to before pipe indicator and after */
for(int p = 0;p<pipeposition;p++){
argsbefore[p]=args[p];
}
/* after */
int e=0;
for(int h = pipeposition+1; h<cnt;h++){
argsafter[e]=args[h];
e++;
}
/* code ... */
if(piping){
pipepid = fork();
if(pid == 0){
/* do child */
if(dup2(pipe1[1],1)==-1){
perror("dup2 child");
exit(1);
}
close(pipe1[1]);
if (execvp(argsbefore[0], argsbefore) < 0) {
printf("exec failed\n");
exit(1);
}
exit(0);
}/* else if error */
else if(pid == -1){
printf("ERROR: fork failed\n");
exit(1);
}/* parent */
else{
if(dup2(pipe1[0],0)==-1){
perror("dup2 parent");
exit(1);
}
close(pipe1[0]);
if (execvp(argsafter[0], argsafter) < 0) {
printf("exec failed\n");
exit(1);
}
}
}
您似乎是在类 unix 系统上这样做的。 如果幸运的话,您的系统可能有一个工具可以报告您的程序执行的每个系统调用( strace -f my_program my_ar gu_ments
会在 Linux 上执行此操作)。
这将为您提供一个列表,列出什么进程在什么时候做了什么,以及某些操作是否有错误代码。 这通常对这些多进程设置有很大帮助。
事实证明我没有关闭所有管道所以第二个命令无法完成,在主父进程中关闭两端后它被修复了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.