嗨,我正在编写一个程序来执行 cat input.txt |排序| uniq在c编程中使用pipe、fork和dup2,但该程序似乎根本不运行任何东西。我在 main() 之后的开头放置了一个 printf ,但我仍然看不到任何输出。我不知道后台发生了什么,也不知道为什么会发生这种情况?
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main(){
printf("we are here");
int pipe1[2];
int pipe2[2];
if(pipe(pipe1)==-1){
perror("failed to pipe\n");
exit(1);
}
int process1=fork();
if(process1<0){
perror("failed to create the first child1\n");
exit(1);
}else if(process1>0){
if(close(pipe1[0])==-1){
perror("failed to close the first pipe read\n");
exit(1);
}
if(dup2(pipe1[1],1)==-1){
perror("failed to duplicate\n");
exit(1);
}
if(close(pipe1[1])==-1){
perror("failed to close the first pipe write\n");
exit(1);
}
execlp("cat","cat","inputs.txt",NULL);
perror("failed to exec\n");
exit(1);
}else if(process1==0){
if(pipe(pipe2)==-1){
perror("failed to pipe\n");
exit(1);
}
int process2=fork();
if(process2<0){
perror("failed to create the first child1\n");
exit(1);
}else if(process2==0){
if(close(pipe2[1])==-1){
perror("failed to close the second pipe write-third process\n");
exit(1);
}
if(dup2(pipe2[0],0)==-1){
perror("failed to duplicate\n");
exit(1);
}
if(close(pipe2[0])==-1){
perror("failed to close the second pipe read-third process\n");
exit(1);
}
execlp("uniq","uniq",NULL);
perror("failed to exec\n");
exit(1);
}else if(process2>0){
if(close(pipe1[1])==-1){
perror("failed to close the first pipe write\n");
exit(1);
}
if(close(pipe2[0])==-1){
perror("failed to close the second pipe read\n");
exit(1);
}
if(dup2(pipe1[0],0)==-1){
perror("failed to duplicate\n");
exit(1);
}
if(dup2(pipe2[1],1)==-1){
perror("failed to duplicate\n");
exit(1);
}
if(close(pipe1[0])==-1){
perror("failed to close the first pipe read\n");
exit(1);
}
if(close(pipe2[1])==-1){
perror("failed to close the second pipe write\n");
exit(1);
}
execlp("sort","sort",NULL);
perror("failed to exec\n");
exit(1);
}
}
}
最佳答案
printf
实际上并不立即打印——它只是将内容放入缓冲区以便稍后打印,或者当缓冲区填满或进程结束时,或者当换行符出现时放入缓冲区。因为你什么都不做,所以它永远不会出现。您可以使用 fflush(stdout); 刷新缓冲区,如果可能有缓冲数据,那么在调用 fork 之前这通常是一个好主意 - 否则缓冲区将被 fork ,因此其内容可能会出现两次。在执行“uniq”之前,永远不要关闭孙子中的
pipe1
。由于pipe1
是“sort”程序的输入,因此它永远不会得到 EOF,并且 sort 永远不会终止。因此,你的程序似乎什么也没做。“uniq”在孙子中运行并输出到标准输出,这是(可能?)您的终端。如果父级(cat)先退出(很可能会),shell 将再次获得控制权,并可能将控制终端从“uniq”下切换出来。这可能会导致 uniq 停止,具体取决于您的终端设置。默认情况下,在大多数系统上,这种情况不会发生(uniq 会在 shell 提示后愉快地写入终端,从而导致可能令人困惑的输出,但也有可能。
关于c - pipe - fork - c - 为什么程序没有任何错误而没有响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51920445/