无法将 printf 重定向到管道

发布于 2025-01-17 07:33:07 字数 885 浏览 2 评论 0原文

我想将printf的输出重定向到管道,但由于某种原因,它似乎行不通。工作是什么是使用

这是我的程序,我的程序只是块

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

如果我用评论行替换

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

好久不见√ 2025-01-24 07:33:07

正如Barmar所建议的那样,要么在输出中添加一个新的行字符(\ n),要么使用fflush()():

fprintf(stderr,“拨打#1!\ n”);

fprintf(stderr,“分叉#1!”);
fflush(stderr);

顺便说一句,它已收到,没有收到;)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文