【发布时间】:2016-10-18 19:45:56
【问题描述】:
我的程序创建子进程并设置管道与它通信。当我尝试从管道读取数据时会出现问题。由于子进程已经结束(我使用wait 来确保)EOF 应该位于数据流的末尾,从而结束读取(如pipe 的手册页中所示)。但是read 只是冻结并等待更多数据的到来。
我在这里错过了什么?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
void setfd(int *in, int *out) {
dup2(out[1], 1);
dup2(in[0], 0);
}
int main(int argc, char *argv[]) {
int status;
int pipe2ch[2], pipe2pr[2];
char *newargv[] = {NULL, NULL};
newargv[0] = argv[1];
pipe(pipe2ch);
pipe(pipe2pr);
setfd(pipe2pr, pipe2ch);
int a;
if (!(a = fork())) {
setfd(pipe2ch, pipe2pr);
execve(newargv[0], newargv, NULL);
exit(1);
} else {
printf("hello!\n");
fflush(stdout);
char str;
wait(&status);
while (read(pipe2pr[0], &str, 1) > 0) {
fprintf(stderr, "%c", str);
}
exit(0);
}
}
【问题讨论】:
-
父进程需要关闭
pipe2pr[1]。它正在阻止自己获得 EOF。
标签: c pipe fork child-process