Skip to content
Advertisement

Can’t redirect printf to pipe

I want to redirect the output of printf to a pipe, but for some reason it doesn’t seem to work. What does work is using write instead.

This is my program

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char **argv) {
  int fd[2];
  pipe(fd);
  pid_t id = fork();
  if (id < 0) {
    fprintf(stderr, "Error while forking #1!");
    exit(1);
  } else if (id == 0) {
    dup2(fd[0], STDIN_FILENO);
    close(fd[1]);
    char msg[200];
    read(STDIN_FILENO, msg, 200);
    fprintf(stderr, "received message: %s", msg);
  } else {
    dup2(fd[1], STDOUT_FILENO);
    close(fd[0]);
    char msg[] = "Hello from parent!n";
    write(STDOUT_FILENO, msg, strlen(msg));
    /* printf("%s",msg); */
    while(wait(NULL)>0);
  }
  exit(EXIT_SUCCESS);
}

if I replace write with the commented line, my program just blocks

Advertisement

Answer

Either add a new line character (n) to your output or use fflush() as Barmar suggests:

fprintf(stderr, “Error while forking #1!n”);

or

fprintf(stderr, “Error while forking #1!”); fflush(stderr);

btw, it’s received, not recieved 😉

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement