我正在尝试使用内存映射文件在Windows(用C#编写)服务和用C ++编写的屏幕保护程序之间共享数据。
虽然如果屏幕保护程序在登录用户的上下文中运行,但如果屏幕保护程序在登录屏幕上运行,则此方法无法正常工作。相反,OpenFileMapping
因未经授权的访问错误而失败。很明显,我错过了一个访问规则(或系统设置可能使这项工作),但我无法弄清楚哪一个。
我的c#侧码:
public CreateMemMappedFile(string fileName)
{
this.rootName = fileName;
var security = new MemoryMappedFileSecurity();
security.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>(
new SecurityIdentifier(WellKnownSidType.WorldSid, null),
MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
security.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>(
new SecurityIdentifier(WellKnownSidType.AnonymousSid, null),
MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
security.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>(
new SecurityIdentifier(WellKnownSidType.NullSid, null),
MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
// printing the SID from the screensaver shows that we are running as Local Service
security.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>(
new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null),
MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
this.handle = MemoryMappedFile.CreateOrOpen(
"Global\\" + fileName, 1024 * 1024,
MemoryMappedFileAccess.ReadWriteExecute
,MemoryMappedFileOptions.DelayAllocatePages,
security, System.IO.HandleInheritability.Inheritable
);
}
我的屏幕保护代码:
TCHAR* myFileName = _T("Global\\myfile");
ipcBufferHandle = OpenFileMapping(FILE_MAP_READ,FALSE,myFileName);
if(ipcBufferHandle == NULL)
{
_tprintf(_T("couldn't open file \"%s\" with error code %d\n"),myFileName,GetLastError());
}
else
{
_tprintf(_T("opened file %s\n"),myFileName);
}
输出couldn't open file "Global\myfile" with error code 5
答案 0 :(得分:0)
如msdn OpenFileMapping所述,定义为
HANDLE WINAPI OpenFileMapping(
_In_ DWORD dwDesiredAccess,
_In_ BOOL bInheritHandle,
_In_ LPCTSTR lpName
);
因此,当您使用bInheritHandle
调用FALSE
时,句柄不会与其他进程共享。试试TRUE
,就像在C#中使用System.IO.HandleInheritability.Inheritable
一样。
ipcBufferHandle = OpenFileMapping(FILE_MAP_READ, TRUE, myFileName);