How to avoid echo closing FIFO named pipes? - Funny behavior of Unix FIFOs

前端 未结 6 1571
面向向阳花
面向向阳花 2020-12-04 08:10

I want to output some data to a pipe and have the other process do something to the data line by line. Here is a toy example:

mkfifo pipe
cat pipe&
cat &         


        
6条回答
  •  一个人的身影
    2020-12-04 08:43

    I enhanced the second version from the Jonathan Leffler's answer to support closing the pipe:

    dir=`mktemp -d /tmp/temp.XXX`
    keep_pipe_open=$dir/keep_pipe_open
    pipe=$dir/pipe
    
    mkfifo $pipe
    touch $keep_pipe_open
    
    # Read from pipe:
    cat < $pipe &
    
    # Keep the pipe open:
    while [ -f $keep_pipe_open ]; do sleep 1; done > $pipe &
    
    # Write to pipe:
    for i in {1..10}; do
      echo $i > $pipe
    done
    
    # close the pipe:
    rm $keep_pipe_open
    wait
    
    rm -rf $dir
    

提交回复
热议问题