在 C 中通过管道进行通信
Communicating via pipes in C
我正在尝试编写这个小程序,其中 parent 和 child 通过管道相互通信,这里的代码有效,除非你 'uncomment' 注释行,而不是某种僵局,我不明白为什么?有什么想法吗?
int main(int argc, char **argv){
int fd[2];
int fd2[2];
pid_t pid;
pipe(fd);
pipe(fd2);
pid = fork();
if(pid==0){
close(fd[1]);
dup2(fd[0],fileno(stdin));
close(fd2[0]);
FILE *output = fdopen(fd2[1],"w");
char buffer[255];
while(fgets(buffer,255,stdin)!=NULL)
printf("child: %s",buffer);
// fprintf(output,"%s",buffer);
} else {
close(fd[0]);
close(fd2[1]);
FILE *output = fdopen(fd[1],"w");
char buffer[255];
while(fgets(buffer,255,stdin)!=NULL)
fprintf(output,"%s",buffer);
//FILE *input = fdopen(fd2[0],"r");
//while(fgets(buffer,255,input)!=NULL)
// printf("Parent: %s",buffer);
}
return 0;
}
父级需要关闭管道的一侧,以便子级能够检测到 end-of-file 并终止。
while(fgets(buffer,255,stdin)!=NULL)
fprintf(output,"%s",buffer);
fclose(output); // does close(fd[1]);
FILE *input = fdopen(fd2[0],"r");
while(fgets(buffer,255,input)!=NULL)
printf("Parent: %s",buffer);
确保一切都已关闭。之后
dup2(fd[0],fileno(stdin));
你应该做的:
close(fd[0]);
当您在两个 (single-threaded) 进程之间同时拥有输入和输出管道时,您可以拥有一些 deadlock, so you need to have an event loop using a multiplexing syscall (generally poll(2)...) and you will either read or write, depending on what is possible. Of course you need to buffer! BTW, in that case, you'll better use low level syscalls(2) without using <stdio.h>
(and if you still do use stdio
, don't forget to fflush(3)....). See also this answer.
(当然我假设是POSIX或Linux系统)
我正在尝试编写这个小程序,其中 parent 和 child 通过管道相互通信,这里的代码有效,除非你 'uncomment' 注释行,而不是某种僵局,我不明白为什么?有什么想法吗?
int main(int argc, char **argv){
int fd[2];
int fd2[2];
pid_t pid;
pipe(fd);
pipe(fd2);
pid = fork();
if(pid==0){
close(fd[1]);
dup2(fd[0],fileno(stdin));
close(fd2[0]);
FILE *output = fdopen(fd2[1],"w");
char buffer[255];
while(fgets(buffer,255,stdin)!=NULL)
printf("child: %s",buffer);
// fprintf(output,"%s",buffer);
} else {
close(fd[0]);
close(fd2[1]);
FILE *output = fdopen(fd[1],"w");
char buffer[255];
while(fgets(buffer,255,stdin)!=NULL)
fprintf(output,"%s",buffer);
//FILE *input = fdopen(fd2[0],"r");
//while(fgets(buffer,255,input)!=NULL)
// printf("Parent: %s",buffer);
}
return 0;
}
父级需要关闭管道的一侧,以便子级能够检测到 end-of-file 并终止。
while(fgets(buffer,255,stdin)!=NULL)
fprintf(output,"%s",buffer);
fclose(output); // does close(fd[1]);
FILE *input = fdopen(fd2[0],"r");
while(fgets(buffer,255,input)!=NULL)
printf("Parent: %s",buffer);
确保一切都已关闭。之后
dup2(fd[0],fileno(stdin));
你应该做的:
close(fd[0]);
当您在两个 (single-threaded) 进程之间同时拥有输入和输出管道时,您可以拥有一些 deadlock, so you need to have an event loop using a multiplexing syscall (generally poll(2)...) and you will either read or write, depending on what is possible. Of course you need to buffer! BTW, in that case, you'll better use low level syscalls(2) without using <stdio.h>
(and if you still do use stdio
, don't forget to fflush(3)....). See also this answer.
(当然我假设是POSIX或Linux系统)