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

int main(){
    int fd[2];
    int old = dup(1);
    char buf[10];
    pipe(fd);       
    dup2(fd[1],1);
    printf("Don't Print!\n");
    dup2(old,1);
    printf("Hello World!\n");
    return 0; 
}

In the above C code "Don't Print" also gets printed.

dup2(fd[1],1)

Sets the default output to the pipe. So printf should write to the output which in this case is the pipe.

dup2(old,1)

if remove this then nothing is printed to the screen but when I include it both strings are printed to the screen. Can someone point out the mistake in my code.

AAB
  • 1,594
  • 2
  • 25
  • 40
  • 3
    The behavior seems to be related to output buffering. If you put `fflush(stdout);` after `printf("Don't print!\n");`, then the program will only print out `"Hello world!"` when you leave in the `dup2(old,1)`. – lurker Sep 01 '17 at 10:46
  • @lurker but wouldn't terminating `\n` cause implicit flush for the first `printf()`? – Sergio Sep 01 '17 at 10:59
  • @lurker Thank you so much. when we say file descriptor = 1 does it point to the same thing as stdout? stdout is a file pointer so do they point to the same file or have I misunderstood, using fflush(stdout) has solved the problem if you write the answer I can mark it as solved. – AAB Sep 01 '17 at 10:59
  • @Sergio that's what I would expect, but there still seems to be a buffering phenomenon going on here, since `fflush(stdout)` changes the behavior. I don't have an explanation. Thus my use of the word *seems* in my original comment. – lurker Sep 01 '17 at 11:01
  • @AAB, yes, the file descriptor for 1 corresponds to standard output. I stopped short of making it an actual answer since I can't, at the moment, explain it. It's currently just an observation. – lurker Sep 01 '17 at 11:02

0 Answers0