Reputation: 29
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 ...
#!/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
slot equal 2
slot equal 1
what the heck am I doing wrong ....
Upvotes: 1
Views: 888
Reputation: 295650
(
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
Upvotes: 3