This is my first question. Hopefully it will not be dumm. Im having problems to write a program that produce "ps aux | grep firefox | tee processes.txt". I succeeded with 1 pipe like "ps aux | grep firefox ", but when I tried to generalize I have problems. My intention is to use pipes to understand them. I know that is possible with open. Any hint would be great!
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/types.h>
int main(void)
{
char *** args = NULL;
pid_t fork_id = -1;
int ** pipes = NULL;
int status = 0;
int i = 0, k = 0;
int check = 0;
args = calloc(3, sizeof(char **));
args [0] = calloc(3, sizeof(char *));
args [1] = calloc(3, sizeof(char *));
args [2] = calloc(3, sizeof(char *));
args[0][0]= "ps";
args[0][1]="aux";
args[0][2]= NULL;
args[1][0]= "grep";
args[1][1]= "firefox";
args[1][2]= NULL;
args[2][0]= "tee";
args[2][1]= "processes.txt";
args[2][2]= NULL;
pipes=calloc(2,sizeof(int *));
for(i=0;i<2;++i){
pipes[i]=calloc(2,sizeof(int));
}
for(i=0;i<2;++i){
pipes[i]=calloc(2,sizeof(int));
check=pipe(pipes[i]);
if(check<0){
perror("pipe");
exit(EXIT_FAILURE);
}
}
for(i=0;i<3;++i){
if ((fork_id = fork()) < 0) {
perror("fork()");
exit(1);
}
if ((i ==0)&& (fork_id == 0)){
close(pipes[i][0]);
close(1);
dup(pipes[i][1]);
close(pipes[i][1]);
execvp(args[i][0], args[0]);
} else if ((i!= 0)&&(i != 2) && (fork_id == 0)){
close(0);
dup(pipes[i][0]);
close(pipes[i][0]);
close(1);
dup(pipes[i][1]);
close(pipes[i][1]);
execvp(args[i][0], args[i]);
} else if ((i==2)&&(fork_id != 0)){
close(pipes[i-1][1]);
close(0);
dup(pipes[i-1][0]);
close(pipes[i-1][0]);
execvp(args[i][0], args[i]);
}
wait(&status);
}
for(i=0;i<2;++i){
for(k=0;k<2;++k){
check=close(pipes[i][k]);
if(check<0){
perror("close pipe");
exit(EXIT_FAILURE);
}
}
}
return(0);
}
thx!!