tags:

views:

72

answers:

3

hello, explain me please how exactly pipe works, for example I have this snippet of the code

set line = ($<)

while(${#line} != 0)
 if(${#line} == 5) then 
  echo line | sort | ./calculate ${1}
 endif 
 set line = ($<)
end

I need to choose all rows with 5 words and after sort it and after transfer, but I'm confused, how will it work, first of all 'while' will take all information and after that transfer it to sort, or every iteration 'while' will do sort? thanks in advance

+2  A: 

Since you're running the echo line | sort | ./calculate ${1} command in every iteration, it will run separately each time through. A pipe just takes the output of the command on the left and feeds it to the input of the command on the right.

Wooble
Wooble: how can I pick ALL information and after that transfer it to sort and after to uniq?
lego69
can I do only echo, and after script ./calculate, inside ./calculate, I'll write sort | uniq...?
lego69
You can probably do all of this within one script, although it would almost certainly be easier in any language except [t]csh; see http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/
Wooble
+1  A: 
tommieb75
tommieb75: in my case can I do only echo, and after script ./calculate, inside ./calculate, I'll write sort | uniq...?
lego69
+2  A: 

In the event that the OP cares about internals, a pipe is often implemented as circular buffer. That is the OS puts aside a chunk of memory and keeps track of what segment of it is currently in use (wrapping around from the end to the beginning as needed):

+-------+
| front |
+-------+
      |             +-------+
      |             | back  |-------\
      V             +-------+        V
+---+---+---+---+---+      +---+---+----+---+---+---+
|   | c | o | n | t |  ... | e | r | \n |   |   |   |  // the buffer itself
+---+---+---+---+---+      +---+---+----+---+---+---+

And we control the behavior with these rules:

  • The wrap-around behavior is accomplished by doing all the position arithmetic modulo the buffer length (watch out if our language uses 1 indexed arrays!).
  • If front and back are ever the same (as in the starting condition), then the pipe is empty and attempts to read from it will block until there is something to read.
  • If back is (front-1) (modulo the length, remember!), the buffer is full and attempts to write will block until there is room.
  • Reading a value from the pipe returns the contents at front, and advances front by one.
  • Writing a value to the pipe advance back by one and inserts the new input at this location.

More complicated schemes involving allowing the buffer to grow when there is a need and memory is available are possible (and indeed are common), and the above can be simplified by make the buffer itself only one character long (meaning that we don't even need front and back anymore) but you pay a cost in terms of a lot of locking and many unnecessary context switches.

dmckee