我在理解 UNIX 系统中管道的正确使用方面遇到了问题。 我有一个创建子进程的主进程。子进程必须运行与父亲不同的程序,他必须进行一些操作,然后 child 必须将结果传达给父亲。 但是在子进程中,我必须在终端上打印这些操作的部分结果。 我正在尝试使用测试程序来这样做,但我现在有点卡住了。这是主要的测试程序
测试.C
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
int mypipe[2];
pid_t pid;
char readbuffer[6];
pipe(mypipe);
if((pid = fork()) == 0){
close(mypipe[0]);
dup2(mypipe[1], STDOUT_FILENO);
execlp("./proc", "./proc", NULL);
} else {
wait(-1);
close(mypipe[1]);
read(mypipe[0], readbuffer, sizeof(readbuffer));
printf("%s", readbuffer);
}
}
./proc程序的c文件是这样的: PROC.C
#include <stdio.h>
int main(int argc, char* argv[]){
printf("check\n");
return 0;
}
使用此解决方案,proc 程序无法在终端上打印任何内容。如何让 proc 程序在终端和管道上打印,以便主程序可以从那里读取??? 谢谢!
最佳答案
即使您将 stdout 重定向到父程序,您仍然可以使用 stderr。当您想要打印到控制台时,只需调用 fprintf(stderr, ...)
而不是 printf(...)
。
关于c - exec 中的标准输出和管道使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23786362/