I am trying to write a program to run ls ../ | grep sg | sort
with execvp and pipe in linux
The program does what I want it to do but the sequence is wrong.
The shell always prompt before the result.
How can I print the result before the shell prompt?
Here is my code:
Code:#include <stdio.h> #include <unistd.h> int main(){ char cmd[255]; int fd[2]; int fd2[2]; int i; pid_t id; pipe(fd); pipe(fd2); for(i = 1; i < 4; i++){ id = fork(); if(id==0){ switch (i){ case(1): close(fd[0]); close(fd2[0]); close(fd2[1]); dup2(fd[1],STDOUT_FILENO); char * args1[] = { "ls", "../", NULL}; execvp(args1[0],args1); break; case(2): close(fd2[0]); dup2(fd2[1],STDOUT_FILENO); close(fd[1]); dup2(fd[0],STDIN_FILENO); char *args2[] = {"grep","sg",NULL}; execvp(args2[0],args2); break; case(3): close(fd[0]); close(fd[1]); close(fd2[1]); dup2(fd2[0],STDIN_FILENO); char *args3[] = {"sort",NULL}; execvp(args3[0],args3); } }else{ waitpid(id); } } return 0; }



LinkBack URL
About LinkBacks



