我们目前利用了flock来限制并发,通常是用一个小括号把需要执行的代码包含起来,这样就会产生一个子shell,带来的问题是父shell无法获得子shell的返回值,昨天刚好Google到这个文章,在这里贴下。
#!/bin/bash
(
flock -s 200
# … commands executed under lock …
) 200>/var/lock/mylockfile
Unfortunately, this invokes a subshell which has the following drawbacks:
You cannot pass values to variables from the subshell in the main shell script.
There is a performance penalty.
The syntax coloring in “vim” does not work properly. :)
This motivated my colleague zImage to come up with a usage form which does not invoke a subshell in Bash:
#!/bin/bash
exec 200>/var/lock/mylockfile || exit 1
flock -n 200 || { echo “ERROR: flock() failed.” >&2; exit 1; }
# … commands executed under lock …
flock -u 200