I want to make a shell and i want to handle multiple pipe. I tried to understand how works dup2() and fork. Normally, fork(), create a new child process who is exactly the same as the father. But when i use dup2 before the fork it doesn't seem to works how i things it should do. But when i use dup2() in the child process it works... I don't understand because normally fork create a copy of the calling process...
Can someone explain why?
This does not work:
int fd = open("toto.txt", O_RDONLY);
char str[10] = {0};
int test[2] = {0, 0};
char *av[] = {"/bin/ls", NULL};
pipe(test);
dup2(test[1], 1);
if (fork() == 0) {
execve(av[0], av, env);
}
else {
wait(NULL);
read(test[0], str, 10);
write(1, str, 10);
}
but this works :
int fd = open("toto.txt", O_RDONLY);
char str[10] = {0};
int test[2] = {0, 0};
char *av[] = {"/bin/ls", NULL};
pipe(test);
if (fork() == 0) {
dup2(test[1], 1);
execve(av[0], av, env);
}
else {
wait(NULL);
read(test[0], str, 10);
write(1, str, 10);
}