1

Consider this code :

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

int main(){
    int pfd[2];
    char buffer[512] = "111803142-Atharva\n", buffer2[512];
    pid_t pid;
    pipe(pfd);
    pid = fork();
    if(pid == 0){
        close(pfd[0]);
        dup2(pfd[1], 1);
        close(pfd[1]);
        /* Closing STDOUT won't print to screen
         * Applying the same logic, after closing pfd[1]
         * data shouldn't go to the pipe ?
        */ 
        printf("%s", buffer);
        exit(0);
    }
    else{
        wait(0);
        close(pfd[1]);
        dup2(pfd[0], 0);
        close(pfd[0]);
        /* 
         * Similarly, after closing pfd[0]
         * scanf should no longer be able to read from it
        */ 
        scanf("%s", buffer2);
    }
    printf("Data : %s\n", buffer2);
    return 0;
}

This code works perfectly fine and its o/p is as follows :

Data : 111803142-Atharva

I have added my doubts in the comments. I want to know why printf() and scanf() are still able to write/read to/from the given file descriptors after closing them?

Atharva
  • 53
  • 1
  • 8
  • 1
    You didn't close the descriptors that you're reading and writing. You closed the descriptors in `pfd`. – Barmar Feb 04 '21 at 06:49
  • 1
    A stream isn't really closed until all the descriptors that refer to it are closed. – Barmar Feb 04 '21 at 06:50

0 Answers0