IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Using flock() in Bash without invoking a subshell

    夜行人发表于 2015-09-18 12:40:53
    love 0

    我们目前利用了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

    原文见:Using flock() in Bash without invoking a subshell



沪ICP备19023445号-2号
友情链接