在命令行上,sort
程序可以输入^D
作为输入结束
$ sort
xyz
def
abc
^D
abc
def
xyz
以下程序使用管道来执行相同的操作,
#include<stdio.h>
#include<stdlib.h>
int main(void){
FILE *pipeFP;
char *str[3] = {"xyz\n", "def\n", "abc\n"};
if((pipeFP = popen("sort", "w")) == NULL){
perror("popen error");
exit(1);
}
/*
popen() performs the following:
1) In parent process, calls pipe() for creating two descriptors, read descriptor is closed, write descriptor is converted to FILE type stream
2) In parent process, calls fork() to create child process and execs with sort program.
3) In child process, write end descriptor is closed, read descriptor is dup2 to stdin
*/
/* Sending string list to sort program*/
fputs(str[0], pipeFP);
fputs(str[1], pipeFP);
fputs(str[2], pipeFP);
pclose(pipeFP);
}
在此计划中,^D
未发送到sort
子流程,sort
如何实现输入的结束?
答案 0 :(得分:0)
pclose()
函数将关闭由popen()
打开的流, 等待命令终止,并返回终止状态 正在运行命令语言解释器的进程。
sort
程序执行与此类似的操作(伪代码):
buffer = []
while true {
line = readline(stdin)
if line == EOF {
break
}
buffer += line
}
print(sort_lines(buffer))
exit
当您致电pclose(pipeFP)
时,会关闭sort
的{{1}}管道(导致stdin
读取EOF),然后等待sort
退出。