排序程序如何遇到EOF?

时间:2016-11-15 18:03:21

标签: c pipe

在命令行上,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如何实现输入的结束?

1 个答案:

答案 0 :(得分:0)

From the pclose man page

  

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退出。