2

flock与命名管道读写引发的死锁

 2 years ago
source link: https://www.lujun9972.win/blog/2019/02/15/flock%E4%B8%8E%E5%91%BD%E5%90%8D%E7%AE%A1%E9%81%93%E8%AF%BB%E5%86%99%E5%BC%95%E5%8F%91%E7%9A%84%E6%AD%BB%E9%94%81/index.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

flock与命名管道读写引发的死锁

尝试用shell写一个多进程爬虫的时候,发现死锁了。代码简化如下:

# 创建命名管道
mkfifo /tmp/ff
exec 99<> /tmp/ff
# 创建生产进程往管道中写入数据
(while :
 do
     flock /tmp/ff -c 'seq 1 10 > /tmp/ff'
 done
) &

# 创建消费进程从管道读取数据
(while :
 do
     flock /tmp/ff -c 'read i </tmp/ff;echo $i'
 done
) &

当消费者进程消费速度快于生产进程时就会发生下面步骤:

  1. 消费者进程持有锁0
  2. 消费者进程从管道读取消息,被阻塞
  3. 生产者往管道发送数据前需要先获取锁0,但是该锁被消费者进程持有,导致生产者也被阻塞。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK