【发布时间】:2017-03-05 07:28:26
【问题描述】:
我在当前目录下有一个名为“tmp”的简单文本文件,我想“cat”这个文件然后“排序”它,我想用一个c程序来充当管道“|”所以我试着用父亲/孩子的谈话来做到这一点。
没想到,程序在“cat”之后挂了,如下所示:
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
int main(){
int pipefd[2];
pipe(pipefd);
int& readfd=pipefd[0];
int& writefd=pipefd[1];
pid_t pid=fork();
if(pid==0){//child
dup2(STDIN_FILENO,writefd);
close(readfd);
execlp("cat","cat","tmp",NULL);
printf("child cat ends\n");
exit(0);
}else{//father
dup2(STDOUT_FILENO,readfd);
close(writefd);
execlp("sort","sort",NULL);
printf("father sort ends\n");
}
int status;
wait(&status);
printf("father exists\n");
return 0;
}
g++编译和运行这个文件,在“cat”tihis文件之后,我什至没有看到“child cat ends”,它只是挂起。
问题出在哪里,如何解决? 谢谢
【问题讨论】:
标签: linux process pipe fork freeze