Is file creation an atom in windows xp?

HI, I would like to use the file system as a lock between two processes, on windows xp. that is, given the file name "file_lock", the process gets a lock, trying to create the file "file_lock" if it does not already exist. If it already exists, the lock cannot be obtained.

i.e.

FileStream fs=new FileStream("c:\\file_lock, FileMode.CreateNew);

Will this work? Is file creation if the file does not already exist atomic?

Thank!

+3
source share
3 answers

Yes, that will work. But not like Mutex for many reasons, including:

  • What if the user does not have access to create this file?
  • , Mutex. .
  • -? ( , , , , ?)
  • .
+7

#, , , .

Java, java.nio.channels.FileLock.

, :

import java.io.RandomAccessFile;
import java.nio.FileLock;
...
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileLock lock = raf.getChannel().tryLock(0L, Long.MAX_VALUE, false);
if (lock != null && lock.isValid()) {
    // You've acquired the lock!
else {
    // You did not acquire the lock
    raf.close();
}

. , . (, raf).

0

, .

  • /
  • ,
  • If the file does not exist or does not have a lock, you can request it.
  • Open the file that opens the lock

This code can help you verify the lock.

public static bool isFileLocked(string filename)
{
    if (!File.Exists(filename)) throw new FileNotFoundException("File not found!", filename);

    FileStream fs = null;
    try
    {
        fs = File.Open(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        return false;
    }
    catch (IOException)
    {
        return true;
    }
    catch (Exception)
    {
        throw;
    }
    finally
    {
        if (fs != null)
        {
            fs.Close();
            fs = null;
        }
    }
}

NTN!

-3
source

All Articles