【发布时间】:2014-05-21 14:35:43
【问题描述】:
我在理解 UNIX 系统中正确使用管道时遇到问题。 我有一个创建子进程的主进程。子进程必须运行与父亲不同的程序,他必须进行一些操作,然后子进程必须将结果传达给父亲。 但是在子进程中,我必须在终端上打印这些操作的部分结果。 我正在尝试使用测试程序来做到这一点,但我现在有点卡住了。这是主要的测试程序
测试.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 文件是这样的: 程序.C
#include <stdio.h>
int main(int argc, char* argv[]){
printf("check\n");
return 0;
}
使用此解决方案,proc 程序无法在终端上打印任何内容。如何使 proc 程序在终端和管道上打印,以便主程序可以从那里读取??? 谢谢!
【问题讨论】: