shell 命名管道,进程间通信
命名管道基础
命名管道也被称为FIFO文件, 在文件系统中是可见的,并且跟其它文件一样可以读写!
命名管道特点:
-
当写进程向管道中写数据的时候,如果没有进程读取这些数据,写进程会堵塞
-
当读取管道中的数据的时候,如果没有数据,读取进程会被堵塞
-
当写进程堵塞的时候,有读进程读取数据,那么写进程恢复正常
-
当读进程堵塞的时候,如果写进程写了数据,那么读进程会读取数据,然后正常执行后面的代码
# 写进程堵塞的情况 [root@ns_10.2.1.242 test]$ echo 1 >p & [1] 17091 [root@ns_10.2.1.242 test]$ jobs [1]+ Running echo 1 > p & [root@ns_10.2.1.242 test]$ cat p 1 [1]+ Done echo 1 > p [root@ns_10.2.1.242 test]$ jobs [root@ns_10.2.1.242 test]$ # 读进程堵塞的情况 [root@ns_10.2.1.242 test]$ cat p & [1] 17351 [root@ns_10.2.1.242 test]$ jobs [1]+ Running cat p & [root@ns_10.2.1.242 test]$ echo 2 > p 2 [root@ns_10.2.1.242 test]$ jobs [1]+ Done cat p
命名管道的作用,不同的进程之间通信,比如在后台执行一个备份进程,然后执行另外一个进程,等待备份完成才会处理想对应的事情!
创建管道的命令:
$ mkfifo /tmp/testpipe
$ mknod /tmp/testpipe p
下面是命名管道的一个应用例子:
reader.sh读取管道的内容,代码如下:
#!/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...."
writer.sh写数据到管道,代码如下:
#!/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
reader和writer调用的例子:
[root@ns_10.2.1.242 test]$ sh reader.sh &
[1] 17053
[root@ns_10.2.1.242 test]$ sh writer.sh test
test
[root@ns_10.2.1.242 test]$ sh writer.sh
Hello from 17057
[root@ns_10.2.1.242 test]$ sh writer.sh quit
stop Reader
[root@ns_10.2.1.242 test]$ sh writer.sh quit
Reader not running
[1]+ Done sh reader.sh
[root@ns_10.2.1.242 test]$ sh writer.sh quit
shell 中的$$
是当前进程的进程ID
分类:
shell
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构