Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- The setup:
- exerciser - A program that prints some stuff, and launches a child process that also prints some stuff. Their prints are setup so that both processes could have the "A" buffered unless stdout is flushed before the fork.
- reader - Launches a child process and sets up a pipe to read it's output. Prints immediately everything it reads from the child. The child runs the exerciser program.
- The problem:
- The terminal somehow deals with the exerciser in a smart way that prevents "A: 10" from showing up twice, the poor reader on the other hand gets "A: 10". What does *reader* have to do differently so that it gets the exact same result as what the terminal shows?
- NOTE: I know how to fix this by adding flushes to exerciser but a part of the problem is that I must solve this by only altering reader.
- ----terminal output----
- <...>/pipe-testing$ ./exerciser
- A: 10
- B: 42
- C: 42
- C: 10
- <...>/pipe-testing$ ./reader
- READER...
- A: 10
- B: 42
- C: 42
- A: 10
- C: 10
- ----exerciser.cpp----
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- int main(){
- int n = 10, status = 0;
- fprintf(stdout, "A: %d\n", n);
- if (fork() == 0){
- n = 42;
- fprintf(stdout, "B: %d\n", n);
- }
- else{
- wait(&status);
- }
- fprintf(stdout, "C: %d\n", n);
- return(0);
- }
- ----reader.cpp----
- #include <stdio.h>
- #include <unistd.h>
- int main(){
- fprintf(stdout, "READER...\n");
- fflush(stdout);
- int pipe_fds[2];
- if (pipe(pipe_fds) == -1){
- fprintf(stdout, "failed to make pipe\n");
- return(0);
- }
- pid_t child_pid = fork();
- if (child_pid == -1){
- fprintf(stdout, "failed to fork\n");
- return(0);
- }
- #define PIPE_READ 0
- #define PIPE_WRITE 1
- if (child_pid == 0){
- close(pipe_fds[PIPE_READ]);
- dup2(pipe_fds[PIPE_WRITE], STDOUT_FILENO);
- dup2(pipe_fds[PIPE_WRITE], STDERR_FILENO);
- char *argv[] = {
- "sh",
- "-c",
- "./exerciser",
- 0
- };
- if (execv("/bin/sh", argv) == -1){
- fprintf(stdout, "failed to execv\n");
- return(0);
- }
- }
- else{
- close(pipe_fds[PIPE_WRITE]);
- char buffer[1024];
- int capacity = sizeof(buffer);
- for (;;){
- ssize_t num = read(pipe_fds[PIPE_READ], buffer, capacity);
- if (num == -1){
- fprintf(stdout, "read error\n");
- return(0);
- }
- else if (num == 0){
- break;
- }
- else{
- fprintf(stdout, "%.*s", (int)num, buffer);
- fflush(stdout);
- }
- }
- }
- return(0);
- }
RAW Paste Data
Copied
Add Comment
Please, Sign In to add comment