Having issues when using dup2 twice within the same process

108 Views Asked by At

I cannot figure out why does this program display only garbage characters when trying to print (at the standard output) some data read from both a file and a pipe. It is interesting that this problem occurs only when I use more than one dup2 instruction within the same process.

#define BSIZE 256

const char in[] = "i.txt";

int main(){
    int id, fd[2];
    pipe(fd);
    id = fork();
    if(id == 0){
        close(fd[0]);
        dup2(fd[1],1);
        printf("blbl");
        close(fd[1]);
    }
    if(id != 0){
        close(fd[1]);
        char tmp[BSIZE];
        int f = open(in,O_RDONLY);
        dup2(f,0);
        fgets(tmp,BSIZE,stdin);
        puts(tmp);
        dup2(fd[0],0);
        fgets(tmp,BSIZE,stdin);
        puts(tmp);
        close(fd[0]);
        close(f);
        wait(NULL);
    }
    return 0;
}
0

There are 0 best solutions below