您尚未登录。

#1 2019-02-15 14:56:39

lujun9972
会员
注册时间: 2016-10-21
帖子: 73

(solved)使用flock fd为什么锁不住文件?

下面这个脚本能正确地发生死锁。

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

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

但是为什么改成下面这个脚本后就死锁不了呢?

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

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

按道理,当消费者进程消费速度快于生产进程时应该发生下面步骤呀:
1. 消费者进程持有锁
2. 消费者进程从管道读取消息,被阻塞
3. 生产者往管道发送数据前需要先获取锁,但是该锁被消费者进程持有,导致生产者也被阻塞。

最近编辑记录 lujun9972 (2019-02-17 21:17:05)

离线

#2 2019-02-15 19:51:35

依云
会员
所在地: a.k.a. 百合仙子
注册时间: 2011-08-21
帖子: 8,942
个人网站

Re: (solved)使用flock fd为什么锁不住文件?

man 2 flock 说:

       Locks created by flock() are associated with an open file description (see open(2)).  This means that duplicate file descrip‐
       tors (created by, for example, fork(2) or dup(2)) refer to the same lock, and this lock may be modified or released using any
       of these file descriptors.

离线

#3 2019-02-17 21:16:43

lujun9972
会员
注册时间: 2016-10-21
帖子: 73

Re: (solved)使用flock fd为什么锁不住文件?

依云 说:
man 2 flock 说:

       Locks created by flock() are associated with an open file description (see open(2)).  This means that duplicate file descrip‐
       tors (created by, for example, fork(2) or dup(2)) refer to the same lock, and this lock may be modified or released using any
       of these file descriptors.

明白了,谢谢

离线

页脚