パイプのexeclp「ソート」入力が中断されました。なぜですか?

パイプのexeclp「ソート」入力が中断されました。なぜですか?

sort待ってるけど何?私はそれを試してみて、execlp("head", "head", "-n", "3", NULL);うまくsort動作します。

#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <assert.h>
int main()
{
  int p[2], cat_pid, sort_pid;
  if (pipe(p) < 0) { assert(0 && "pipe fail"); }
  if ((cat_pid = fork()) == 0) { dup2(p[1], 1); execlp("cat", "cat", "text", NULL); assert(0 && "cat fail"); }
  if ((sort_pid = fork()) == 0) { dup2(p[0], 0); execlp("sort", "sort", NULL); assert(0 && "sort fail"); }
  waitpid(sort_pid, NULL, 0);
}

入力は次のtextとおりです

hello
world
foo
bar

ベストアンサー1

EOFを待っている間、sortパイプの書き込み側を閉じる必要があります。 1つは完了後に閉じ、catもう1つは親プロセスにあります。親パイプの書き込み側を閉じると、すべてがうまくいきます。

man 7 pipe

パイプの書き込みの終わりを参照するすべてのファイル記述子が閉じられている場合、パイプがread(2)を試みるとファイルの終わりが表示されます(read(2)は0を返します)。

おすすめ記事