Unix C - redirecting stdout to a channel and then back to stdout

I am not sure what the following can be done because I cannot find any questions / results through Google. I want to change stdout fork () to a channel, and then return it back to normal stdout.

This is what I have:

FirstExecutable:

int main() { int fd[2]; //Used for pipe int processID; if(pipe(fd) == -1) { printf("Error - Pipe error.\n"); exit(EXIT_FAILURE); } if((processID = fork()) == -1) { fprintf(stderr, "fork failure"); exit(EXIT_FAILURE); } if(processID == 0) { int newFD = dup(STDOUT_FILENO); char newFileDescriptor[2]; sprintf(newFileDescriptor, "%d", newFD); dup2 (fd[1], STDOUT_FILENO); close(fd[0]); execl("./helloworld", "helloworld", newFileDescriptor, NULL); } else { close(fd[1]); char c[10]; int r = read(fd[0],c, sizeof(char) * 10); if(r > 0) printf("PIPE INPUT = %s", c); } } 

HelloWorld

 int main(int argc, char **argv) { int oldFD = atoi(argv[1]); printf("hello\n"); //This should go to pipe dup2(oldFD, STDOUT_FILENO); printf("world\n"); //This should go to stdout } 

Output Required:

 world PIPE OUTPUT = hello 

Actual output:

 hello world 
+4
source share
1 answer

Try to change

  printf("hello\n"); 

to

  printf("hello\n"); fflush(stdout); 

Here's the problem of buffering. For performance reasons, FILE descriptors do not always output immediately after they are written. Instead, they accumulate text in the internal buffer.

There are three buffering modes, unbuffered, row buffered, and buffered block. Unbuffered pens are always written immediately (stderr does not load). Linear buffered descriptors wait until the buffer is full or a newline ( '\n' ) is printed (stdout is string buffering if it refers to a terminal). Blocked buffered descriptors wait until the buffer is full (stdout is a block buffer if it is not a terminal).

When your helloworld program starts, stdout goes to the channel, not to the terminal, so it is configured as a buffer. Therefore, printf calls simply store the text in memory. Since the buffer does not fill up, it only turns red when stdout closes, which in this case occurs when the program exits.

But by the time the program exited, file descriptor 1 (stdout) had been restored to refer to the parent source stdout, and not to the channel. Thus, buffered output ends up being written to the original output.

fflush forcibly writes buffer text.

+3
source

All Articles