I'm going to write a very small shell and in order to implement pipe,I use redirection.But there's some problems here:
Code:
void do_with_pipe(char **argv1,char **argv2)
{
int pid1,pid2;
int pipe1[2];
if(pipe(pipe1)<0)
{
perror("pipe failure");
exit(EXIT_FAILURE);
}
pid1=fork();
if(pid1<0)
{
perror("fail to fork");
exit(1);
}
else if(pid1==0)
{
pid2=fork();
if(pid2<0)
{
perror("fail to fork");
exit(1);
}
if(pid2==0)
{
if(dup2(pipe1[0],STDIN_FILENO)==-1)
perror("fail to dup");
close(pipe1[0]);
close(pipe1[1]);
execvp(argv2[0],argv2);
}
else{
if(dup2(pipe1[1],STDOUT_FILENO)==-1)
perror("fail to dup");
close(pipe1[0]);
close(pipe1[1]);
execvp(argv1[0],argv1);
}
}
else{
if(waiting)
waitpid(pid1,NULL,0);
else
waiting=YES;
}
}
This is the function to do the work and I'm sure the arguments are right.but the result doesn't print until the program end.For instance:
loyoo:~/programming/kernel$ ./shell
loyoo>>ls|sort
loyoo>>
loyoo>>
loyoo>>
loyoo>>q
01139-1.pdf
01139-1.tar.bz2
explain.ppt
info
info.odt
Linux_schedule.doc
shell
shell.c
syllabus.doc
loyoo:~/programming/kernel$
Why???