/********************************************************
 * This program runs "ls -al | grep arg1 > arg2 "       *
 * This uses the strategy that parent creates pipe, but *
 * does not do redirection, the two child processes do it.*
 ********************************************************/

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

int main(int argc,char**argv) 
{
    if (argc < 3) {
        fprintf(stderr, "usage: lsgrep arg1 arg2\n");
        exit(1);
    }
    // Parent process creates pipe	
    int fdpipe[2];
    pipe(fdpipe);
 
    // fork for "ls"
    int ret= fork();
    if(ret==0) {
        // Inside child process intended to run ls
        dup2(fdpipe[1],1);  // stdout now points to fdpipe[1], writing end of pipe
        close(fdpipe[0]);
        close(fdpipe[1]);
        char * args[3];
        args[0]="ls";
        args[1]="-al";
        args[2]=NULL;
        execvp(args[0], args);
        // error in execvp
        perror("execvp");
        exit(1);
    }

    close(fdpipe[1]);
    // Inside parent process, create outfile
    int fd=open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0600);
    if (fd < 0){
        perror("open");
        exit(1);
    }

    // fork for grep
    ret= fork();
    if(ret==0) {
        dup2(fd,1);
        //close(fd);
        dup2(fdpipe[0], 0);
        close(fdpipe[0]);
        char * args[3];
        args[0]="grep";
        args[1]=argv[1];
        args[2]=NULL;
        execvp(args[0], args);
        // error in execvp
        perror("execvp");
        exit(1);
    }

    //close(fdpipe[0]);
    //close(fd);
    // Parent waits for grep process to complete
    waitpid(ret,NULL);
    fprintf(stderr, "All done!!\n");
} 

