0

This post explains how to put file write lock on regular files.

But is it possible to put a lock on a yaml file, so only one script at a time can write to it?

I am using YAML::Syck, if that makes a difference.

Community
  • 1
  • 1
Sandra Schlichting
  • 25,050
  • 33
  • 110
  • 162

2 Answers2

1

You can lock a file using flock. You'll need to open the file first as flock operates on filehandles.
Alternatively you can use LockFile::Simple from CPAN.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • How can I lock a yaml file with flock? Doesn't it require a file handle? – Sandra Schlichting Mar 30 '11 at 12:02
  • @Sandra: YAML::Syck's LoadFile() takes a file name or a file handle. You'd open the file before calling the function, flock it, then pass the handle to LoadFile. It does not, however, prevent any other process from reading or writing the file unless those other processes also use flock. – runrig Mar 30 '11 at 14:31
1

As others have said, use flock. Also, see perlfaq5 under "How can I lock a file".

It's important to note that it's advisory locking anyway, so there is no need to actually lock the .yaml file. You can just lock a lock file (maybe yourfile.yaml.lock) and unlock it when done.

This also gives you the capability to say "this block of operations requires exclusive access", rather than just limit your exclusivity to a single file.

TardisX
  • 687
  • 4
  • 9