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?


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.

  • may i know if this is limited to 3 shell scripts? What if there are more? Cause I am using this locking system as a server processing backend. So, I wont know how many threads will exist. – Vignesh T.V. Nov 23 '15 at 17:27
  • As long as they all seek to acquire a lock on the same lockfile, there's no limit. Just be aware that performance may suffer if one thread takes too long. – Oli Nov 23 '15 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.