0

I am trying to use dup2 to communicate between parent and child in the following code.

#include <stdio.h> 
#include <unistd.h> 

void main(int argv, char *argc) { 
    int testpipe[2]; 
    pipe(testpipe); 
    int PID = fork(); 
    if (PID == 0) { 
        dup2(testpipe[0], 0); 
        close(testpipe[1]); 
        execl("./multby", "multby", "3", NULL); 
        close(testpipe[0]); 
        close(0); 
    } else { 
        dup2(testpipe[1], 1); 
        close(testpipe[0]); 
        printf("5"); 
        fclose(stdout); 
        close(testpipe[1]); 
        wait(NULL); 
    }  
}

I understand that fclose is needed to write the output into stdout. However, in the case I do not use stdout or stdin, (that is, I do not use file descriptors 1 and 0), is there anyway for me to get the file pointer being reference by a file descriptor so that I can get the file pointer as an argument for fclose?

  • I don't think I understand what you have in mind with "in the case that I do not use stdout or stdin". The only way that there exist any `FILE *` streams besides `stdout, stdin, stderr` is if you have opened one with `fopen`, `fdopen`, etc, in which case it is up to you to remember what it is. In general there is no mapping from file descriptors to streams, for the simple reason that a given file descriptor may not have any stream associated with it at all. (It also might have more than one.) – Nate Eldredge Feb 17 '20 at 02:11
  • 1
    I don't think any of this works the way you think it does. The actual pipe descriptor does no buffering, it's only the standard I/O library, and this buffering does not cross process bounds: in the child, the standard output stream has nothing to do with any library buffering done in the parent. Also, the `execl()` in the child *replaces* the child process with the program being executed, so the lines after it only run on failure - you're generally done after `exec*` – Steve Friedl Feb 17 '20 at 02:49
  • See also [Why is it that my pipe does not read in the `printf` despite replacing stdin?](https://stackoverflow.com/q/60250374/15168) — this question is also asked in a comment there. – Jonathan Leffler Feb 17 '20 at 02:58

0 Answers0