r305_dm/TP5/Exo1/exo1_2.c

46 lines
928 B
C
Raw Normal View History

2023-10-05 22:42:05 +02:00
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Usage: %s <file>\n", argv[0]);
return EXIT_FAILURE;
}
int pip, fd[2], outfile, d;
char buf;
pip = pipe(fd);
assert(pip != -1);
pid_t p = fork();
assert(p != -1);
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;
}
close(outfile);
return EXIT_SUCCESS;
}