#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <err.h>

/*
         __ 
    ___( o)>
    \ <_. )
     `---' 

Coic coic
*/

int duper(char **argv, char *output){


    //int fd[2];
    //pipe(fd);
    if(!argv || !*argv || !output) return 1;
    
    int wstatus;
    pid_t pid = fork();

    if(pid < 0) return 1;

    //Child
    else if (pid == 0){

        // ouverture en mode write 
        FILE *file = fopen(output, "w");
        if(!file) exit(-1);

        
        int fno = fileno(file);
        if(dup2(fno, STDOUT_FILENO) == -1) exit(-1);
        
        fclose(file);

        execvp(argv[0],argv);
        
        exit(0);
    }

    // Uncle... Daddy, mommy, well ikd
    else {

        if(waitpid(pid, &wstatus, 0) ==  -1) return -1; 

        if(WIFEXITED(wstatus)) printf("My child send me %i.\n", WEXITSTATUS(wstatus));
        
    }
    return 0;

}

/*
int main(int argc, char **argv)
{
    if(argc > 3) 
    duper(argv + 2, argv[1]);
}
*/
