BASH: Best architecture for reading from two input streams

后端 未结 2 1902
长情又很酷
长情又很酷 2020-12-21 00:42

Simple script here:

a) constantly read from a socket and store values in an associative array
b) constantly read values from s

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-21 01:03

    Don't know if this is fully practical and atomic enough in the described context, but using a client / server model and named pipes it's possible to create a while-loop that can distinguish between lines coming from a fifo or stdin.

    The server constantly reads lines from a socket (/tmp/to) as well as lines from stdin (which is being redirected to the server via /tmp/to).

    However, lines from stdin get marked by the del byte (\177) to be the first byte of the line.

    Then the (backgrounded) client while-loop uses this first-byte-of-line to distinguish lines of different origin.

    # terminal window 1
    
    # server
    (
    rm -f /tmp/to /tmp/from
    mkfifo /tmp/to /tmp/from
    while true; do 
      while IFS="" read -r -d $'\n' line; do 
        printf '%s\n' "${line}"
      done /tmp/from &
      bgpid=$!
      exec 3>/tmp/to
      exec 4/tmp/to;
    exec 4&3
    ) 
    #kill -TERM $serverpid
    
    
    # terminal window 2
    echo hello > /tmp/to
    

提交回复
热议问题