3

Here is my code and I can't get it to work.

int pfd = open("file", O_WRONLY, 0777);
int saved = dup(1);
close(1);
dup(pfd);
close(pfd);
printf("This goes into file\n");

// restore it back
dup2(saved, 1);
close(saved);
printf("this goes to stdout");

I have added some edits to my code.

posixKing
  • 408
  • 1
  • 8
  • 17

1 Answers1

3

You need to check the return values of your function calls. For most functions, you should check for error conditions. Doing so might have revealed the problem that if you want open() to create the requested file in the event that it does not initially exist, then you need to add the O_CREAT flag.

But that's not your main problem here -- you are dealing with a buffering issue. The output from the first printf() is buffered in memory, so even though file descriptor 1 refers to your file at the time that printf() is called, the data you write do not immediately get flushed to the destination file. You then restore the original stdout file handle, so when the data are actually flushed, they go to the (restored) original stdout. Solve this by fflush()ing before switching stdout back:

int pfd = open("file", O_WRONLY | O_CREAT, 0777);
int saved = dup(1);

close(1);
dup(pfd);
close(pfd);
printf("This goes into file\n");
fflush(stdout);  // <-- THIS

// restore it back
dup2(saved, 1);
close(saved);
printf("this goes to stdout");

Note also that dup2() is cleaner and safer for duping a file descriptor onto a specific file descriptor number. You do that when you restore, but you should also do it for the initial redirection.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • My bad, it was a mistake on my part. Will retract the comment. Thanks for your answer. fflush does the trick – posixKing Dec 08 '17 at 18:35