4

我正在尝试使用内存映射文件在 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

4

1 回答 1

0

msdn OpenFileMapping所述,定义为

HANDLE WINAPI OpenFileMapping(
  _In_  DWORD dwDesiredAccess,
  _In_  BOOL bInheritHandle,
  _In_  LPCTSTR lpName
);

因此,当您调用bInheritHandlewith时FALSE,句柄不会与其他进程共享。尝试TRUE,就像您在 C# 中使用System.IO.HandleInheritability.Inheritable.

ipcBufferHandle = OpenFileMapping(FILE_MAP_READ, TRUE, myFileName);
于 2013-08-05T21:10:34.607 回答