pipes in unix
Kartik Subbarao
subbarao at SunOS.Princeton.EDU
Sun May 5 11:53:05 AEST 1991
In article <37580001 at hpopd.pwd.hp.com> dcc at hpopd.pwd.hp.com (Daniel Creswell) writes:
>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?
No, it doesn't know. Rather, it doesn't care. The typical unix pipe-tools
just take standard input, perform some operation on it (sort in this case,
and print their results to stdout. So, what's happening here is that you're
dup'ing the read end of the pipe to sort's stdin, so when it reads from 0,
it reads from the pipe.
>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?
I hope you have a main() that's surrounding this code. Otherwise, I can see
no problem.
-Kartik
--
internet# rm `df | tail +2 | awk '{ printf "%s/quotas\n",$6}'`
subbarao at phoenix.Princeton.EDU -| Internet
kartik at silvertone.Princeton.EDU (NeXT mail)
SUBBARAO at PUCC.BITNET - Bitnet
More information about the Comp.unix.questions
mailing list