pipes in unix

Daniel Creswell dcc at hpopd.pwd.hp.com
Thu May 2 17:55:32 AEST 1991


I'm trying to suss how pipes between processes work (hey I dont get to play
with UNIX all day so I'm a bit dumb!) and came across the following exmaple:

The following example uses pipe to implement the command
string "ls | sort":

     #include <sys/types.h>
     pid_t pid;
     int pipefd[2];

    /*  Assumes file descriptor 0 and 1 are open  */
              pipe (pipefd);

	      if ((pid = fork()) == (pid_t)0) 
	      {
              close(1);      /* close stdout */
              dup (pipefd[1]);
	      execlp ("ls", "ls", (char *)0);
	      }
	      else
	      if (pid > (pid_t)0) 
	      {
	      close(0); /* close stdin  */
              dup (pipefd[0]);
	      execlp ("sort", "sort", (char *)0);
	      }

What I wanna know is how does this work. I've looked up 'dup' and discovered
that it duplicates a descriptor which will be carried across an 'exec' but
dont understand how the recipient program knows its got a pipe. Does it know?
Is it simple that dup replaces stdin and stdout if so why? because it doesn't
seem to do that in the above code?

I know I'm missing something here...would some kind person please tell me what
it is?

Cheers,
	Dan.

P.S. Could you post responses to notes it'll be easier than emailing me!

Thanks for your ears...



More information about the Comp.unix.questions mailing list