【发布时间】:2017-05-18 21:18:27
【问题描述】:
我正在尝试使用内存映射文件为 IPC 编写简单的发送方/接收方类。 所以我的代码有问题,但我不明白我在这里做错了什么:
[Serializable]
public struct MessageData
{
public int PID;
public IntPtr HWND;
public string ProcessName;
public string ProcessTitle;
}
....
public static class MMF
{
private const int MMF_MAX_SIZE = 4096; // allocated memory for this memory mapped file (bytes)
private const int MMF_VIEW_SIZE = 4096; // how many bytes of the allocated memory can this process access
public static void Write()
{
var security = new MemoryMappedFileSecurity();
// Create a SecurityIdentifier object for "everyone".
SecurityIdentifier everyoneSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
security.AddAccessRule(new AccessRule<MemoryMappedFileRights>(everyoneSid, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("Global\\mmf1", MMF_MAX_SIZE, MemoryMappedFileAccess.ReadWrite))
{
using (MemoryMappedViewStream mStream = mmf.CreateViewStream(0, MMF_VIEW_SIZE))
{
var p = Process.GetCurrentProcess();
MessageData msgData = new MessageData();
msgData.HWND = p.MainWindowHandle;
msgData.PID = p.Id;
msgData.ProcessName = p.ProcessName;
msgData.ProcessTitle = p.MainWindowTitle;
// serialize the msgData and write it to the memory mapped file
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(mStream, msgData);
mStream.Flush();
mStream.Seek(0, SeekOrigin.Begin); // sets the current position back to the beginning of the stream
//MessageBox.Show("Done");
}
}
}
}
现在我尝试从主应用程序表单中测试这段代码:
...
private void button1_Click(object sender, EventArgs e)
{
MMF.Write();
}
Visual Studio 2015 Community 中的进程会挂起。进程运行,但表单界面没有响应。我只能暂停或停止进程。这是在using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("Global\\mmf1", ... 字符串上停止。
我假设应用程序无法创建文件,但没有任何例外。
所以,如果我将地图名称更改为“mmf1”(不带“Global”前缀),一切正常,应用程序工作正常。但据我所知,this answer 和 MSDN:
在文件映射对象名称前加上“Global\”允许进程相互通信,即使它们在不同的终端服务器会话中。
如果我理解正确,需要前缀“Global\”来与任何应用程序交互我的内存映射文件,无论它们以何种权限运行。
特别是因为我正在尝试为“每个人”设置文件访问权限。
UPD。 此代码在 Win 7 / Win 8.1 x64 上测试。结果是一样的。
【问题讨论】:
-
禁用您的反恶意软件产品并重试。
-
感谢您的回复,但我在开发人员 PC 上没有任何反邮件软件。该程序的用户是否也必须关闭防病毒软件才能使该应用程序正常工作?
标签: c# winforms ipc memory-mapped-files