BASH local and flock

2019-08-07 21:30发布

问题:

I try to use a flock like here https://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 ....

回答1:

( 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 local flock