0

sort is waiting, but what? I tried execlp("head", "head", "-n", "3", NULL); instead sort and it works fine.

#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);
}

input text is:

hello
world
foo
bar

1 Answer 1

1

As sort is waiting for EOF you need to close pipe' write end. One is closed once cat is done and another one is in parent process. Close pipe' write end in parent and everything should go fine.

man 7 pipe

If all file descriptors referring to the write end of a pipe have been closed, then an attempt to read(2) from the pipe will see end-of-file (read(2) will return 0).

1
  • Note: if p[1] was closed AFTER sort's fork, this fork needs to close it itself! I got it, TY!
    – amordo
    Commented Feb 17, 2022 at 17:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .