David Douthitt writes:

...

> | ....And same is true when system is used.  Why can you believe a file
> | existence check and a creation in the shell are atomic?
> 
> Normally, I would agree.  But the (shell) code in question is this:
> 
>    set -o noclobber
>    cat /dev/null 2> /dev/null > process.lock
> 
> The real question would be in the code for the redirection operator '>'
> This code would attempt to create an empty file (cat /dev/null), redirect
> it to process.lock ( > process.lock), and throw away error messages
> ( 2> /dev/null).  Without the throw-away, one gets a message like this
> if the file exists:
> 
> /usr/bin/ksh[2]: process.lock: file already exists
> 
> Without the "noclobber" option, the error does not appear, and the
> existing file would be "overwritten" - which in this case of locks,
> would be meaningless.

But you have to look, how it is implemented in the corresponding
shell. I have not looked into the sources but I dare to guess it is
something like:

    if (noclobber && stat(filename, &st) >= 0) {
       fprintf(stderr, "%s: %s: file already exists\n", argv[0], filename);
    } else {
       fout = fopen(filename, "w");
       if (fout == NULL) {
          :
       }
       :
    }

That means the shell will do the existance test for you! But it can be 
interrupted between the call to 'stat' and 'fopen'. It suffer from the 
same problem as my Ruby solution. Only the gap where that problem
could occure is, of course, much smaller in C than in Ruby.

I have to thank you to put my nose onto that problem again. I have
already tried to minimize the risks in my module. But I could do it
better, I will simply code the relevant function in C. Then the
time-of-danger will be as small as in your shell solution.

I will put an updated version into the contrib dir ASAP.

> | File locking are usually implemented with atomic operations such as
> | symlink or mkdir.  These operations are atomic --- an existence check
> | and a creation of a named symbolic link/directory can not be interrupted
> | by any process.
> 
> How would one use this?  Neither a symbolic link nor a directory would
> have much use as a lock file, I would think.

It depends! The advantage using a directory would be, that nobody
could break the mkdir call. So if I am trying to create a directory my 
call to mkdir will succeed or fail. If it was successful it means *I*
have created that directory. If it fails it *could* mean, others have
already created it. The same is true for call to symlink.

I have thought to use this for my module, but decide against it,
because the filelock mechanism used by sendmail do not work with
directories as lock. As I want to make the whole thing as portable as
possible, symlink also was not a choice here.

...

\cle

-- 
Clemens Hintze  mailto: c.hintze / gmx.net