BASH地方和羊群 [英] BASH local and flock

查看:96
本文介绍了BASH地方和羊群的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用羊群喜欢这里 http://stackoverflow.com/a/169969
但在函数中...我尝试从羊群中的部分更新本地变量(区域设置的功能),但似乎没有更新...

猫test.sh

 #!/斌/庆典功能_job_worker()
{
        当地Z = 1
        当地结果=
        (
                #等待锁/var/lock/.manager.exclusivelock(FD 200)
                涌向-x -w 10 200 ||返回                Z = 2
                回声插槽等于$ Z        )200 GT; /var/lock/.manager.exclusivelock        回声插槽等于$ Z}_job_worker

./ test.sh

 插槽等于2
插槽等于1

你到底我做错了....


解决方案

创建一个子shell。这是一个单独的进程,有自己的变量和状态 - 它不只是当地人不逃避子shell,但全局变量,文件句柄的变化,当前目录的变化,以及(pretty了)一切<。 / p>

使用 {} 来代替创建范围重定向同一个shell中运行,而不是在开始块子shell。

这就是:

  _job_worker(){
        当地Z = 1的结果=
        {
                #等待锁/var/lock/.manager.exclusivelock(FD 200)
                涌向-x -w 10 200 ||返回
                Z = 2
                回声插槽等于$ Z
        } 200 GT; .manager.exclusivelock
        回声插槽等于$ Z
}_job_worker

I try to use a flock like here http://stackoverflow.com/a/169969 but within a function ... and I try to update a local variable (locale to the function) from within the flock part, but it seems not update ...

cat test.sh

#!/bin/bash

function _job_worker()
{
        local z=1
        local result=


        (
                # Wait for lock on /var/lock/.manager.exclusivelock (fd 200)
                flock -x -w 10 200 || return

                z=2
                echo "slot equal $z"

        ) 200>/var/lock/.manager.exclusivelock

        echo "slot equal $z"

}

_job_worker

./test.sh

slot equal 2
slot equal 1

what the heck am I doing wrong ....

解决方案

( and ) create a subshell. This is a separate process, with its own variables and state -- it's not just locals that don't escape a subshell, but global variables, file handles changes, current directory changes, and (pretty much) everything else.

Use { and } instead to create a block with scoped redirections running inside the same shell rather than starting a subshell.

That is:

_job_worker() {
        local z=1 result=
        {
                # Wait for lock on /var/lock/.manager.exclusivelock (fd 200)
                flock -x -w 10 200 || return
                z=2
                echo "slot equal $z"
        } 200>.manager.exclusivelock
        echo "slot equal $z"
}

_job_worker

这篇关于BASH地方和羊群的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆