0

I want to simulate this Unix command :

cat file.txt | sort | tail -4

I followed the technique, but it does not work, it remains blocked. Maybe i need to use something else when there are files. I used two pipes, and two processes and i used two DUP in a single process, maybe that's wrong.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main()
{
  int p1[2];
  int p2[2];

  if(pipe(p1))
  {
    perror("pipe1");
    exit(0);
  }

  if(pipe(p2))
  {
    perror("pipe2");
    exit(0);
  }

  switch(fork())
  {
    case -1: perror(" fork1 error ");
             exit(0);

    case  0: close(STDOUT_FILENO);
             (void)dup(p1[1]);
             close(p1[1]);
             close(p1[0]);
             execlp("cat", "cat", "file.txt", NULL);
             exit(0);
    default: 
            switch(fork())
            {
              case -1: perror(" fork2 error ");
               exit(0);

              case  0: close(STDIN_FILENO);
                       (void)dup(p1[0]);
                       close(p1[1]);
                       close(p1[0]);

                       close(STDOUT_FILENO);
                       (void)dup(p2[1]);
                       close(p2[1]);
                       close(p2[0]);

                       execlp("sort", "sort", NULL);
                       exit(0);

              default: 
                       wait(NULL);
                       close(STDIN_FILENO);
                       (void)dup(p2[0]);
                       close(p2[0]);
                       close(p2[1]);
                       execlp("tail", "tail", "-4", NULL); 
            }             
  }
}

this is the file.txt :

g
f
d
b
c
a
e
5
  • 1
    Unless you're doing this to learn, I'd suggest using libpipline -- libpipeline.nongnu.org Commented Apr 29, 2012 at 17:39
  • 1
    Why do you call wait(3)? Commented Apr 29, 2012 at 17:40
  • To until the end of the two process Commented Apr 29, 2012 at 17:44
  • 1
    I found the solution. The problem is i'm not closing the pipes as i should. Commented Apr 29, 2012 at 17:48
  • 1
    You'll probably want dup2() instead of dup(). Commented Apr 29, 2012 at 17:55

1 Answer 1

1

The parent process never closes the pipe p1 so its child keep trying to read on it. Add close(p1[0]); close(p1[1]); before the execlp("tail", "tail", "-4", NULL);.

Also note that you should not wait(NULL): this is another hang waiting to happen when file.txt is big and starts to fill the pipe buffer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.