Subject: Re: reading from named pipes
To: None <current-users@NetBSD.ORG, mouse@Collatz.McRCIM.McGill.EDU>
From: Danny Boulet <danny@BouletFermat.ab.ca>
List: current-users
Date: 05/11/1995 07:41:27
> 
> 
> > I have two processes reading from the same named pipe.
> > The output written to the pipe seems to get evenly split between the
> > two processes.
> 
> > Feature or bug?
> 
> Feature, I would say.  Traditional pipes have always worked this way,
> as have sockets.  And (I just now tried it on SunOS 4.1.3) named pipes
> do this under at least one other OS.
> 
> 					der Mouse
> 
> 			    mouse@collatz.mcrcim.mcgill.edu
> 

>From the perspective of the operating system, this is a feature (i.e.
defined behaviour with a few caveats).

Note that the consumers do NOT necessarily get round-robin access.

Assume both consumers are essentially:

    while ( 1 ) {
	rlen = read(pipefd,buffer,sizeof(buffer);
	do_something_with_result(buffer,rlen);
    }

The following scenario is possible:

    - consumer A reads some stuff and then gets suspended by the
      scheduler (i.e. somewhere inside of "do_something_with_result").
    - consumer B reads some stuff, completes a call to
      "do_something_with_result" and then reads some stuff again.
      Eventually, consumer B gets suspended by the scheduler.
    - consumer A resumes, returns from "do_something_with_result" and
      then reads some more stuff.

Note that consumer B could complete quite a large number of read operations
between the pair of reads that consumer A does.  I.e. There is NO guarantee
that the two consumers will take turns.

On the other hand, each read is going to remove data from the pipe (i.e.
it will be gone and the other consumer never sees it).  Consequently, in
the long run, the two consumers will probably each see roughly 50% of the
data (there are an awful lot of caveats on that last 'probably').

This is a classic race condition.  I can think of a few situations where
it would make sense to do the above.  Unfortunately, from the perspective
of the application, doing this (two consumers of a resource without any other
mechanism to control access to the resource) is almost always a bug.

-Danny