My program, called T gets 2 arguments form the command line: "command1 and its parameters" and "command2 and it's parameters" and the idea is that I then create a child process that will be the first command (the command on the left of ' | ') and the parent will be the second command. The child process wil load the intended process with execl and its output will be redirected to the pipe, the parent process will wait for the child's output and use it as its input. This is my idea but I cant get it to work. Any help on what's wrong with my code would be heavily apreciated.
/* Trying to implement "|" Example: ls -l | wc must be written as ./T "ls -l" "wc" */ #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]) { int p[2]; unsigned char i, sizeComm; unsigned char *command; unsigned char *route; unsigned char *param; int state; pid_t pid; //buffers command=calloc(15,sizeof(unsigned char)); route=calloc(17,sizeof(unsigned char)); param=calloc(30,sizeof(unsigned char)); //initializing pipe pipe(p); pid=fork(); if(pid==0) { //child process is the first command to be executed (command on the left of "|") // will send its output to parent process (command on the right of "|") close(p[0]); //stdout now will be sent to parent process dup2(p[1],STDOUT_FILENO); //Now the command must be parsed //concatenating name of the command to "/bin/" or else access denied for(i=0; ( command[i] = (argv[1])[i] ) != ' '; i++) ; strcpy(route,"/bin/"); strcat(route+5,command); // parsing parameters to be sent to execl //pointing to the first space after the first command sizeComm = strlen(command); for(i=0;( param[i] = (argv[1])[i+sizeComm] ) ;i++) ; //Now I just call the first command execl(route,command,param,(char*)NULL); free(command); free(route); free(param); close(p[1]); } if(pid>0) { //Parent process is the second command, must wait for its child. close(p[1]); //stdin is now what the child process sent dup2(p[0],STDIN_FILENO); //parsing the second command //concatenating name of the command to "/bin/" or else access denied for(i=0; ( command[i] = (argv[2])[i] ) != ' '; i++) ; strcpy(route,"/bin/"); strcat(route+5,command); // parameters // parsing parameters to be sent to execl sizeComm = strlen(command); for(i=0;( param[i] = (argv[2])[i+sizeComm] ) ;i++) ; //waiting for the output of command1 before executing command2 wait(&state); execl(route,command,param,(char*)NULL); close(p[0]); free(command); free(route); free(param); } if(pid<0) { perror("Failiure"); return -1; } return 0; }