Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

272
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda