Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

263
Vistas
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

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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 ;)

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda