in reply to News script again

Just to add to Zaxo's above comment, flock() eq 'good' ...

People new to CGI programming often miss the fact that the http server will start multiple copies of your process, and any data files read/written could be done so at the same time. While reads are ok, all processes should be using flock() so they do not read partial data, or write at the same time as another process.

Moral of the story : Pleas use flock() for any CGI process which reads/writes data files.
"They shall not overcome. Whoever told them that the truth shall set them free was obviously and grossly unfamiliar with federal law."
    -- John Ashcroft

Replies are listed 'Best First'.
Re: Re: News script again
by Anonymous Monk on Oct 03, 2001 at 15:30 UTC
    G'day

    I'd be more than happy to use flock()...

    If I knew what it was
    Its syntax and
    when to use it and why?

    Thanks again
    La Grenouille

      flock allows you to lock a file, so other process that check for locks will wait until the file is unlocked to use it. This way 2 processes will not try to write a file at once, which usually results in one of the writes being lost.

      See perldoc -f flock, search for flock on this site and look at KM's RE: File Locking for more information.

      The name flock is a contraction of "file lock". The syntax for it is available via perldoc -f flock, or here.

      Why? Because if two programs, or two instances of the same program (as you may get from a web server) attempt to rewrite the same file at the same time you lose changes.

      For example:

      • prog 1 reads file
      • prog 2 reads file
      • prog 1 writes file
      • prog 2 writes file, losing prog 1's changes

      Worse:

      • prog 1 reads file
      • prog 1 starts rewriting file, and gets halfway
      • prog 2 reads file (but only reads the first half)
      • prog 1 finishes writing
      • prog 2 rewrites file
      Now half the file is simply missing!

      By calling flock() before starting to read the file, the problem will be avoided, as prog 2 will simply stall until prog 1 releases the lock.

      Ok, here some help to get you started :

      1. flock() is a function used to lock files.
      2. See the basic info here
      3. When to use it. flock() is used whenever two (or more) processes may try to access the same file at the same time. It gives you the abiality to have one process write at a time, and all reads will wait until the wrtie is complete.

      There are some limitations to flock().
      1. If there is a process which does not check for a lock, it will not stop it from writting. This means, that for flock() to work correctly, all processes which read/write the data file need to impliment flock().
      2. flock() is unimplimented on some OS's.

      "They shall not overcome. Whoever told them that the truth shall set them free was obviously and grossly unfamiliar with federal law."
          -- John Ashcroft