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

int main(int argc, char** argv){
	if (argc != 2){
		printf("Usage : %s <file>", argv[0]);
		exit(EXIT_FAILURE);
	}
	pid_t p;
	int pip, fd[2], outfile, d;
	char buf;
	pip = pipe(fd);
	if (pip == -1){
		perror("Erreur lors de la création du pipe.");
		exit(EXIT_FAILURE);
	}
	p = fork();
	outfile = open(argv[1], O_WRONLY|O_CREAT, 0644);
	switch(p){
		case 0 :
			close(fd[0]);
			d = dup2(fd[1], 1);
			execl("/usr/bin/ls", "ls", "-i", "-l", "/tmp", NULL);
			close(fd[1]);
			exit(0);
		default :
			close(fd[1]);
			while(read(fd[0], &buf, sizeof(char)) > 0){
				write(outfile, &buf, sizeof(char));
			}
			break;
		case -1:
			perror("Erreur lors de création d'un nouveau processus");
			exit(EXIT_FAILURE);
	}
	close(outfile);
	return EXIT_SUCCESS;
}
