How to Use named shared memory reasonably and securely on the. NET platform to share data between processes

Source: Internet
Author: User

Traditional applicationsProgramThere are multiple methods for high-speed data transmission between different processes. As the mainstream of Win32, many programs will see the createfilemapping function, which allows you to share how to establish a kernel object reasonably and securely, and the background and operation process of the entire environment.

[Structlayout (layoutkind. Sequential)]
Internal class security_attributes
{
Public int nlength;
Public safelocalmemhandle lpsecuritydescriptor;
Public bool binherithandle;
Public security_attributes ()
{
This. nlength = 12;
This. lpsecuritydescriptor = new safelocalmemhandle (intptr. Zero, false );
}
}

[Suppressunmanagedcodesecurity, hostprotection (securityaction. linkdemand, mayleakonabort = true)]
Internal sealed class safefilemappinghandle: safehandlezeroorminusoneisinvalid
{
[Securitypermission (securityaction. linkdemand, unmanagedcode = true)]
Internal safefilemappinghandle (): Base (true ){}
[Securitypermission (securityaction. linkdemand, unmanagedcode = true)]
Internal safefilemappinghandle (intptr handle, bool ownshandle)
: Base (ownshandle)
{
Sethandle (handle );
}
[Reliabilitycontract (consistency. willnotcorruptstate, Cer. Success), dllimport ("kernel32.dll", setlasterror = true, exactspelling = true)]
Private Static extern bool closehandle (intptr handle );
Protected override bool releasehandle ()
{
Return closehandle (handle );
}

}

 

[Suppressunmanagedcodesecurity, hostprotection (securityaction. linkdemand, mayleakonabort = true)]
Internal sealed class safelocalmemhandle: safehandlezeroorminusoneisinvalid
{
Internal safelocalmemhandle (): Base (true ){}
[Securitypermission (securityaction. linkdemand, unmanagedcode = true)]
Internal safelocalmemhandle (intptr existinghandle, bool ownshandle)
: Base (ownshandle)
{
Sethandle (existinghandle );
}
[Dllimport ("advapi32.dll", charset = charset. Auto, setlasterror = true)]
Internal static extern bool convertstringsecuritydescriptortosecuritydescriptor (string stringsecuritydescriptor, int stringsdrevision, out safelocalmemhandle psecuritydescriptor, intptr securitydescriptorsize );
[Reliabilitycontract (consistency. willnotcorruptstate, Cer. Success), dllimport ("kernel32.dll")]
Private Static extern intptr localfree (intptr hmem );
Protected override bool releasehandle ()
{
Return (localfree (handle) = intptr. Zero );
}
}

Internal sealed class safeviewoffilehandle: safehandlezeroorminusoneisinvalid
{
[Securitypermission (securityaction. linkdemand, unmanagedcode = true)]
Internal safeviewoffilehandle (): Base (true ){}
[Securitypermission (securityaction. linkdemand, unmanagedcode = true)]
Internal safeviewoffilehandle (intptr handle, bool ownshandle): Base (ownshandle) {sethandle (handle );}
Protected override bool releasehandle ()
{
If (unmapviewoffile (handle ))
{
Base. Handle = intptr. zero;
Return true;
}
Return false;
}
}

 

Const int file_map_copy = 0x0001;
Const int file_map_write = 0x0002;
Const int file_map_read = 0x0004;
Const int file_map_all_access = 0x0002 | 0x0004;

Const int page_readonly = 0x02;
Const int page_readwrite = 0x04;
Const int page_writecopy = 0x08;
Const int page_execute = 0x10;
Const int page_execute_read = 0x20;
Const int page_execute_readwrite = 0x40;

Const int sec_commit = 0x8000000;
Const int sec_image = 0x1000000;
Const int sec_nocache = 0x10000000;
Const int sec_reserve = 0x4000000;

 

Const int invalid_handle_value =-1;

 

[Dllimport ("kernel32.dll", charset = charset. Auto, setlasterror = true)]
Static extern safefilemappinghandle openfilemapping (INT dwdesiredaccess, bool binherithandle, string lpname );

[Dllimport ("kernel32.dll", charset = charset. Auto, setlasterror = true)]
Static extern safefilemappinghandle createfilemapping (intptr hfile, security_attributes lpfilemappingattributes, int flprotect, int dwmaximumsizehigh, int dwmaximumsizelow, string lpname );
[Reliabilitycontract (consistency. willnotcorruptstate, Cer. Success), dllimport ("kernel32.dll", exactspelling = true)]
Static extern bool unmapviewoffile (intptr lpbaseaddress );

[Dllimport ("kernel32.dll", setlasterror = true, exactspelling = true)]
Static extern safeviewoffilehandle mapviewoffile (safefilemappinghandle handle, uint dwdesiredaccess, uint dwfileoffsethigh, uint dwfileoffsetlow, uintptr dwnumerofbytestomap );

The safe establishment of the handle of an unmanaged platform is a place I highly recommend, because if the kernel object is not released, memory leakage will occur, causing serious harm .. In the. NET platform, pinvoke supports multiple sending policies, so it is especially important to use secure handle whenever possible.

The following describes the environment, method flow, and sequence parameters.
Environment:
The main body of the file ing is the file. All ing will create an address ing for the file stream in the process area where the current view is established. The job for this memory address is the job for the file, because a ing is established in the memory, each process can read and write its own ing zone independently, and finally call a method to synchronously refresh the file stream (not implemented in this article ). For more details, please go to Google. Note that the creation of the named object will be related to the creation process.

Method flow and sequence parameters:
The first priority of createfilemapping is the handle of a file. If invalid_handle_value is used, the default memory page file will be used as the ing. The second is a security setting. If it is null, the default security control table is used. The third is read/write permissions and ing settings, which support or operations. The third bit is the 64-bit maximum high address (0, because there will not be such a large file) The fourth bit is the 64-bit maximum low address (not the actual object's physical memory length) the fifth place is the name. If it is null, it is an anonymous object. We will not discuss it here.

Openfilemapping is the first access permission, and the second is whether the sub-process can share the handle Resource (involving handle replication ). The third digit is the name.

Mapviewoffile: the first is the handle Instance obtained by the preceding two methods, the second is the access permission, and the third and fourth are the displacement of the view in the sense of createfilemapping. The fifth digit is the number of ing bytes. If the value is 0, the entire block is mapped.

From creating (or opening) ing to creating a view, you can now use the read/write operations on the memory in the. NET environment.
You can use the copy method of the marshal class. The dangerousgethandle () method on the security handle established earlier returns the Security pointer of the job.

Handle can be automatically released.

Now the end part is complete. I was going to use this to implement some functions. Later I found that it does not meet my requirements.CodeI am about to abandon it. In general, I have seen ten special implementation cases that cannot be found. c ++ is the main one, and these authors habitually make packaging classes.

Please refer to my suggestions after reading this article. Don't pack more on it. It's enough for simple data transfer and sharing, I don't think it is necessary to add a class named by myself. In case of improper design, it will attract people ...... of course, if you deliberately want to do something, unless you also add a lot of atomic operations and other synchronization job control to it, I cannot fly over to oppose it. That's it. I hope everyone can learn the knowledge.

 
Finally, these methods and constants have been completely tested. Please feel free to use them.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.