If I redirect stdout into a pipe with dup2, how can I get it back again?
(there is no output)Code:#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main () {
FILE *pin, *pout;
int pp[2], i, chr;
pipe(pp);
pout = fdopen(pp[0], "r");
pin = fdopen(pp[1], "w");
close(pp[0]);
dup2(pp[1],1);
puts("hello");
printf("test");
fclose(pin); // ??
close(pp[1]); // ??
while((chr=fgetc(pout)) != EOF) printf("%c",chr);
close(pp[0]);
fclose(pout); // everything closed
puts("hello");
fflush(NULL); // and flushed
}
I recognize that "It is not very useful for a single process to use a pipe to talk to itself", however, I'm trying to get the logic of c redirection. In other contexts (eg. shell scripting) redirecting stdin and stdout is always simple and straightforward -- if you exec 3>$1 you can later exec 1>&3. But in this example, stdout never comes back, even if the file descriptor it was redirected into gets closed, etc.
Also strange to me is that stderr seems to be included (puts).