随笔 - 13  文章 - 0  评论 - 2  阅读 - 34152

shell 命名管道,进程间通信

命名管道基础

命名管道也被称为FIFO文件, 在文件系统中是可见的,并且跟其它文件一样可以读写!

命名管道特点:

  1. 当写进程向管道中写数据的时候,如果没有进程读取这些数据,写进程会堵塞

  2. 当读取管道中的数据的时候,如果没有数据,读取进程会被堵塞

  3. 当写进程堵塞的时候,有读进程读取数据,那么写进程恢复正常

  4. 当读进程堵塞的时候,如果写进程写了数据,那么读进程会读取数据,然后正常执行后面的代码

     # 写进程堵塞的情况
     [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

posted on   琣厵  阅读(7679)  评论(0编辑  收藏  举报
编辑推荐:
· .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语句:使用策略模式优化代码结构
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示