Z
ZhukovL
I'm having some trouble implementing the handling of multiple pipes in
a shell I'm writing. I was hoping someone could point me in the right
direction because I really cant see where I'm going wrong. Its
supposed to work as follows: main shell forks off a child shell, the
child shell sets up the pipes and forks off n-1 other shells (where n
is the total number of commands). Each child shell sets its pipe file
descriptors then execs to whatever its supposed to be, the original
child shell is the final command which the main shell waits for it to
return.
Everything works except for the piping, below is the relevant code:
//the number of execution blocks (each will be a sperate command)
int n;
int i;
pid_t pid[n];
int pfd[n-1][2];
..
..
..
pid = fork();
if(pid == 0){
/*The main child shell*/
/*Create n-1 pipes*/
while(i < (n-1) ){
printf("I is : %d", i);
pipe(pfd);
printf("Pipe created and put into pfd[%d]\n", i);
i++;
}
i = 1;
//call fork() for the first n-1 processes
while (i < n ){
pid[i-1] = fork();
if(pid[i-1] == 0){
break;
}
i++;
}
//then the child shells do some stuff here
//this is where I need help
if( blist->pipes == 1 || i == n && n != 1 ){
printf("\nI'm supposed to pipe because __commands->pipes = %d",
blist->pipes);
//redirect STDIN
if(i > 1) dup2(pfd[i-2][0], STDIN);
//redirect STDOUT
if(i < n) dup2(pfd[i-1][1], STDOUT);
//close all pipe file descriptors
d = 0;
while (d < n){
close(pfd[d][0]);
close(pfd[d][1]);
d++;
}
}
a shell I'm writing. I was hoping someone could point me in the right
direction because I really cant see where I'm going wrong. Its
supposed to work as follows: main shell forks off a child shell, the
child shell sets up the pipes and forks off n-1 other shells (where n
is the total number of commands). Each child shell sets its pipe file
descriptors then execs to whatever its supposed to be, the original
child shell is the final command which the main shell waits for it to
return.
Everything works except for the piping, below is the relevant code:
//the number of execution blocks (each will be a sperate command)
int n;
int i;
pid_t pid[n];
int pfd[n-1][2];
..
..
..
pid = fork();
if(pid == 0){
/*The main child shell*/
/*Create n-1 pipes*/
while(i < (n-1) ){
printf("I is : %d", i);
pipe(pfd);
printf("Pipe created and put into pfd[%d]\n", i);
i++;
}
i = 1;
//call fork() for the first n-1 processes
while (i < n ){
pid[i-1] = fork();
if(pid[i-1] == 0){
break;
}
i++;
}
//then the child shells do some stuff here
//this is where I need help
if( blist->pipes == 1 || i == n && n != 1 ){
printf("\nI'm supposed to pipe because __commands->pipes = %d",
blist->pipes);
//redirect STDIN
if(i > 1) dup2(pfd[i-2][0], STDIN);
//redirect STDOUT
if(i < n) dup2(pfd[i-1][1], STDOUT);
//close all pipe file descriptors
d = 0;
while (d < n){
close(pfd[d][0]);
close(pfd[d][1]);
d++;
}
}