1

I have an application that runs in Citrix environment. The application can be run simultaneously by several users in different user sessions. In my application I am writing to a file which should be mutually exclusive across all the user sessions. I tried Mutex to avoid writing to a file from different user sessions but using Mutex failed as in some scenarios different user sessions could not detect whether the Mutex object was already created.

Could any one tell me which of the below approach is better to achieve mutual exclusion across all the user sessions:

  1. Using Named pipes : If named pipe already exists then application will wait till the pipe gets closed by the application instance which had opened it. Otherwise create the named pipe to indicate the acquiring of lock.
  2. Using a lock file: Create a normal file on disk to indicate the acquiring of lock and delete when unlock needs to be done.
aJ.
  • 34,624
  • 22
  • 86
  • 128

1 Answers1

3

You don't need to use a lock file. You can use the built in file system sharing mechanism.

When you open the file by calling CreateFile() you determine the sharing access for subsequent attempts to open the file with the dwShareMode parameter. For example, set this to 0 and no other process will be able to open the file.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Thanks. But I would like open later when the other process finishes its task of writing to that file. Basically mutual exclusion – aJ. Mar 07 '11 at 09:17
  • 1
    @aJ When a process is finished writing, it calls `CloseHandle` on the file handle and then it's available again. Basically the interface to the filesystem already implements mutual exclusion for you. You really must not try to do it any other way! – David Heffernan Mar 07 '11 at 09:19
  • But the process has to wait till the other process calls CloseHandle. Does OS supports any mechanism to "know" when the other process finishes its writing? – aJ. Mar 07 '11 at 09:21
  • 1
    @aJ If the writing is quick and there's little contention, then you could just loop with a sleep. Otherwise you could go back to your mutex and use the global namespace rather than the local namespace which I'd guess was what you did wrong before. – David Heffernan Mar 07 '11 at 09:26
  • Ah! Global namespace--that might help me. Let me try. Thanks a lot. – aJ. Mar 07 '11 at 09:31
  • @aJ Prepend "Global\" to your mutex name. It's all in the CreateMutex documentation. I'd still set the share mode properly because other processes (not your process with the mutex protection) may try to write to the file. – David Heffernan Mar 07 '11 at 09:33
  • Why not use CreateFile() as David mentioned and then just call CloseHandle manually when your program is done writing to the file? – Trevor May 06 '11 at 17:42