无法将 printf 重定向到管道
我想将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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如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 ;)