Sabrina 2019-12-22
命名管道也被称为FIFO文件, 在文件系统中是可见的,并且跟其它文件一样可以读写!
命名管道特点:
当读进程堵塞的时候,如果写进程写了数据,那么读进程会读取数据,然后正常执行后面的代码
# 写进程堵塞的情况 [_10.2.1.242 test]$ echo 1 >p & [1] 17091 [_10.2.1.242 test]$ jobs [1]+ Running echo 1 > p & [_10.2.1.242 test]$ cat p 1 [1]+ Done echo 1 > p [_10.2.1.242 test]$ jobs [_10.2.1.242 test]$ # 读进程堵塞的情况 [_10.2.1.242 test]$ cat p & [1] 17351 [_10.2.1.242 test]$ jobs [1]+ Running cat p & [_10.2.1.242 test]$ echo 2 > p 2 [_10.2.1.242 test]$ jobs [1]+ Done cat p
命名管道的作用,不同的进程之间通信,比如在后台执行一个备份进程,然后执行另外一个进程,等待备份完成才会处理想对应的事情!
$ mkfifo /tmp/testpipe $ mknod /tmp/testpipe p
#!/bin/bash
# filename: reader.sh
# 逐行读取管道中的内容
pipe=/tmp/testpipe
trap "rm -f $pipe" EXIT
if [[ ! -p $pipe ]]; then
mkfifo $pipe
fi
while true
do
if read line <$pipe; then
if [[ "$line" == ‘quit‘ ]]; then
break
else
echo $line
fi
fi
done
echo "Stop reader...."#!/bin/bash
# writer.sh
# 把当前进程的pid写到管道
pipe=/tmp/testpipe
if [[ ! -p $pipe ]]; then
echo "Reader not running"
exit 1
fi
if [[ "$1" ]]; then
echo "$1" >$pipe
else
echo "Hello from $$" >$pipe
fi[_10.2.1.242 test]$ sh reader.sh & [1] 17053 [_10.2.1.242 test]$ sh writer.sh test test [_10.2.1.242 test]$ sh writer.sh Hello from 17057 [_10.2.1.242 test]$ sh writer.sh quit stop Reader [_10.2.1.242 test]$ sh writer.sh quit Reader not running [1]+ Done sh reader.sh [_10.2.1.242 test]$ sh writer.sh quit
shell 中的$$是当前进程的进程ID
Ncat作HTTP server: