Ubuntu – Lock file and release it

fileslock

I have multiple threads running from different terminal windows in ubuntu trying to write to the same file.

I would like to lock the file via terminal while writing so that the other thread(s) has to wait to write till the lock is released. How do I do this?

Best Answer

Using flock is probably the easiest way for three competing shell scripts. Let's assume you have a single path to a lock file called /run/lock/myapp.

# in terminal 1
flock /run/lock/myapp sleep 10

# in terminal 2
flock /run/lock/myapp echo "hello"

If you run these at about the same time (the first first though) the second will wait 10 seconds before running.

If you're deep in another programming language, there will be other ways to handle this better.

Related Question