pipes in unix

mike.stefanik mike at bria.UUCP
Sun May 5 12:34:04 AEST 1991


In an article, 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:

[ code example deleted ]

|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?

Since dup() will duplicate a descriptor *always using the first descriptor
available* you are using (in my opinion: abusing) the feature of dup to
replace stdout and stdin.

Think of your file desciptor table as an array like this:

        +---+
        | 0 |	/dev/tty (standard input)
        +---+
        | 1 |	/dev/tty (standard output)
        +---+
        | 2 |	/dev/tty (standard error)
        +---+
        | 3 |	pipefd[0], pipe input
        +---+
        | 4 |	pipefd[1], pipe output
        +---+

When you close standard output with close(1), the table is like this:

        +---+
        | 0 |	/dev/tty (standard input)
        +---+
        | 1 |
        +---+
        | 2 |	/dev/tty (standard error)
        +---+
        | 3 |	pipefd[0], pipe input
        +---+
        | 4 |	pipefd[1], pipe output
        +---+

When you subsequently call dup(), it starts walking forward through
the table, using the first available slot that you have.  So, after
the dup(pipefd[1]) call, things look like this:

        +---+
        | 0 |	/dev/tty (standard input)
        +---+
 +----> | 1 |   pipe (standard output)
 |      +---+
 |      | 2 |	/dev/tty (standard error)
 |      +---+
 |      | 3 |	pipefd[0], pipe input
 |      +---+
 +---->	| 4 |	pipefd[1], pipe output
        +---+

When you then execl() the program, it will start writing to descriptor 1,
which is now the pipe.  When your program forked (inheriting the pipe
descriptors) it did a similar thing, replacing it's standard input with the
input on the pipe -- thus it could read what was being written.

-- 
Michael Stefanik, MGI Inc, Los Angeles | Opinions stated are never realistic
Title of the week: Systems Engineer    | UUCP: ...!uunet!bria!mike
-------------------------------------------------------------------------------
If MS-DOS didn't exist, who would UNIX programmers have to make fun of?



More information about the Comp.unix.questions mailing list