2

My Dll writes data into a file "Sample.txt".

If the Dll is loaded by two processes, then the Sample.txt will be written by both the processes.

In that case, only the process which writes first into file keeps on writing into it. I couldnt see the second process's data in that Sample.txt. I use Mutex for synchronizing between processes.

My code is as below,

HANDLE MLock = CreateMutex(NULL,FALSE,L"MLock");
WaitForSingleObject(MLock,INFINITE);
ofstream fp;
fp.open("Sample.txt",ios::app);
fp <<  GetCurrentProcessID();
fp.close();
ReleaseMutex(MLock);

I can see only the first process's ID in the Sample.txt. Only if the first process gets killed the second process data is being written. Where am i going wrong?

Note: This issue occurs only in few machines.

Sel_va
  • 588
  • 5
  • 25
  • 1
    Did you emit the error handling from your example? Note that `CreateMutex` can return `NULL`. – default Feb 07 '17 at 09:54
  • Also, `WaitForSingleObject` can return different results as well. You can check an example [here](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686927(v=vs.85).aspx) for how to use Mutexes with `CreateMutex` and `WaitForSingleObject` – default Feb 07 '17 at 09:57
  • Although, I would probably recommend using [`lock_guard`](http://en.cppreference.com/w/cpp/thread/lock_guard) instead. – default Feb 07 '17 at 09:59
  • @Default lock_guard works inter-process? And just now checked , 'yes' i am getting NULL in CreateMutex. But GetLastError is not returning any error. – Sel_va Feb 07 '17 at 10:07
  • @Default Sorry for previous comment. GetLastError returns ACCESS_DENIED – Sel_va Feb 07 '17 at 10:15
  • If you are getting access denied from a createmutex call, then it is possible the calling processes are running in different sessions. Can your DLL be loaded from a service? or can the host machine be running remote as well as local logins, over something like RDP? I discuss this issue with mutexes on my site at http://www.bobmoore.dx.am/Win32/w32tip7.htm – Bob Moore Feb 07 '17 at 10:19
  • I tried OpenMutex referring this link https://msdn.microsoft.com/en-us/library/windows/desktop/ms682411(v=vs.85).aspx . But Even that returned ACCESS_DENIED – Sel_va Feb 07 '17 at 10:56
  • @BobMoore This cannot be loaded as a service. and it should run in Local machine only. Starving for a solution – Sel_va Feb 07 '17 at 11:38

1 Answers1

0

Try this:

HANDLE MLock = CreateMutex(NULL,FALSE,L"MLock");
if (NULL == MLock)
      MLock = OpenMutex(MUTEX_ALL_ACCESS,FALSE,L"MLock");

if (NULL == MLock){
   // error return 
}

WaitForSingleObject(MLock,INFINITE);
//...
Laszlo
  • 769
  • 9
  • 19