简体   繁体   English

来自两个进程的同一文件写入失败

[英]write fails in same file from two processes

My Dll writes data into a file "Sample.txt". 我的Dll将数据写入文件“ Sample.txt”。

If the Dll is loaded by two processes, then the Sample.txt will be written by both the processes. 如果Dll由两个进程加载,则两个进程将写入Sample.txt。

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. 我在该Sample.txt中看不到第二个进程的数据。 I use Mutex for synchronizing between processes. 我使用Mutex在进程之间进行同步。

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. 我只能在Sample.txt中看到第一个进程的ID。 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. 注意:仅在几台计算机上会出现此问题。

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);
//...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM