Shared memory of process communication

Source: Internet
Author: User
Tags function prototype int size

Shared Memory
Shared memory allows two unrelated processes to access the same logical memory. Shared memory is a very efficient way to share and pass data between two running processes. Memory that is shared between different processes is usually scheduled as the same piece of physical memory. Processes can connect the same piece of shared memory to their own address space, and all processes can access the addresses in the shared memory as if they were allocated by the C-language function malloc. If a process writes data to shared memory, the changes will immediately affect any other process that can access the same piece of shared memory.

Shared memory does not provide a synchronization mechanism, that is, there is no automatic mechanism to prevent the second process from starting to read the shared memory until the first process ends the write operation. So we usually need to use other mechanisms to synchronize access to shared memory.

http://blog.csdn.net/xiaoliangsky/article/details/40024657

Shared memory-related functions

1 Creating shared Memory Shmget

function prototypes: int shmget (key_t key, size_t size, int shmflag);

Key: Rules for identifiers
Size: Number of bytes in shared bucket
Shmflag: Read and Write permissions
Return value: The ID of the shared store was successfully returned, failure returned-1
-----------------------------------------------
Key identifies the value of the shared memory: 0/ipc_private. When the value of key is ipc_private create a new memory, if the value of key is 0, and the parameter SHMFLG is set ipc_private this flag, then a new shared memory will also be created.
In the IPC communication mode, whether using Message Queuing or shared memory, or even semaphores, each IPC object has a unique name called "key". With the key, the process is able to identify the object being used. The relation of "key" to the IPC object is like the file name to the file, through the filename, the process can read and write the data within the file, even multiple processes can share a file. In the IPC communication mode, the use of "keys" also enables an IPC object to be shared by multiple processes.
All data structures in the Linux system that represent the IPC objects in Systems v include a IPC_PERM structure that contains the key values for the IPC object, which is used to find the reference identifier of the IPC object in System V. If you do not use the key, the process will not be able to access the IPC object because the IPC object does not exist in the memory used by the process itself.
In general, you want your program to be able to pre-contract a unique key value with other programs, but it is not always possible, because your program cannot select a key value for a piece of shared memory. Therefore, the key is set to Ipc_private, so that the operating system ignores the key, establishes a new shared memory, specifies a key value, and returns this shared memory IPC identifier ID. Instead, the identifier ID of this new shared memory tells other processes to implement it either by deriving a child process or by writing to a file or pipeline after the shared memory is established.

int size (unit byte byte)
-----------------------------------------------
The size is the length of the shared memory to be established. All memory allocation operations are in page units. So if a process only requests a single byte of memory, the memory will also be allocated a full page (the default size of pace_size=4096 bytes on a page in the I386 machine) this way, the newly created shared memory size is actually the page size that is adjusted from the size parameter. That is, if size is 1 to 4096, the amount of shared memory actually requested is 4K (one page), and 4097 to 8192, the amount of shared memory actually requested is 8K (two pages), and so on.

int SHMFLG
-----------------------------------------------
SHMFLG mainly related to some signs. Valid include Ipc_creat and IPC_EXCL, and their function is equivalent to open () O_creat and O_EXCL.
Ipc_creat if the shared memory does not exist, create a shared memory or open the operation.
IPC_EXCL only if the shared memory does not exist, the new shared memory is established, or an error is generated.

If you use the Ipc_creat,shmget () function alone either returns an operator of the shared memory that already exists, or returns an identifier for the newly created shared memory. If the ipc_creat and IPC_EXCL flags are used together, Shmget () returns an identifier for the newly created shared memory, if the shared memory already exists, or 1 is returned. The IPC_EXEL flag itself does not make much sense, but working with the IPC_CREAT flag can be used to guarantee that the resulting object is new, rather than opening an existing object. The read and write licenses for the user specify Shm_r and Shm_w, (shm_r>3) and (shm_w>3) are a set of read and write licenses, while (shm_r>6) and (SHM_W>6) are global read and write licenses.

return value
-----------------------------------------------
The identifier for the shared memory was successfully returned; the -1,errno storage error reason was not successfully returned.
The EINVAL parameter size is less than shmmin or greater than Shmmax.
Eexist shared memory due to pre-established key, but already exists.
The shared memory caused by the EIDRM parameter key has been deleted.
The ENOSPC exceeds the maximum amount of shared memory that the system allows to establish (Shmall).
The shared memory referred to by the ENOENT parameter key does not exist, and the parameter SHMFLG is not set ipc_creat bit.
Eacces does not have permissions.
Enomem core memory is low.


2 Connecting shared memory Shmat

Function prototypes: void* shmat (int shmid, const void *shmaddr, int shmflag)

A shared memory identifier of Shmid is connected to the shared memory, and the shared memory area object is mapped to the call when the connection succeeds
The address space of the process, which can then be accessed as if it were in local space.

-----------------------------------------------

Shmid Shared memory identifier, ID returned by the Shmget function
Shmaddr pointing out where the shared memory appears at the address of the process memory, when it is directly specified as NULL, the kernel has its own decision
An appropriate location for the address.
SHMFLG shm_rdonly: Read-only mode, other read-write mode

return value

-----------------------------------------------

Success: The shared memory address of the attachment is good
Error:-1, wrong reason is present in error
Note: After fork, the child process inherits the connected shared memory address. After exec, the child process is automatically detached from the shared memory address.
Once the process is finished, the connected shared memory address is automatically detached.

Error code

-----------------------------------------------

Eacces: No permissions have been specified to connect shared memory
EINVAL: Invalid parameter shmid or shmaddr
Enoeme: Insufficient core memory


3 "Detach" Shared memory Shmdt

Function prototype: int SHMDT (const void *SHMADDR)

Used to disconnect the address space from the shared memory attach point and prevent this process from accessing this slice of shared memory.
SHMADDR: The starting address of the connected shared memory

return value

-----------------------------------------------

Successful return 0
Error returned-1, the cause of errors exists in error
Note: This function call does not delete the specified shared memory area, but only the shared memory that was previously connected with the Shmat function (attach) is detached (detach) the current process

Error code

-----------------------------------------------

EINVAL: Invalid parameter shmaddr


4 Managing Shared Memory Shmctl

function prototypes: int shmctl (int shmid, int cmd, struct shmid_ds *buf)

Administrative shares are not saved.

-----------------------------------------------

Shmid Shared Memory identifiers
CMD ipc_stat: Get the state of shared memory, copy the SHMID_DS structure of shared memory to BUF;
Ipc_set: Change the state of shared memory, copy the UID, GID, mode in Shmid_ds to the SHMID_DS structure of shared memory.
Ipc_rmid: Delete this piece of shared memory
BUF shared memory management structure. See the contributing Memory Kernel structure definition section for details.

return value

-----------------------------------------------

Successful return 0
Error returned-1, the cause of errors exists in error

Error code

-----------------------------------------------

eaccess: Parameter cmd is ipc_stat, does not have permission to read the shared memory
Efault: Parameter buf points to an invalid memory address
EIDRM: Shared memory with identifier Msqid has been deleted

EINVAL: Invalid parameter cmd or shmid
Eperm: Parameter cmd is ipc_set or ipc_rmid, but does not have sufficient permissions to execute


One last example:

#include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include < sys/shm.h> #include <sys/ipc.h> #include <sys/wait.h> #include <error.h> #define Memory_size             1024int Main () {int wpid;int status;int failed;int Shmid;char *addr;pid_t pid;struct Shmid_ds buf;failed = 0;shmid = Shmget (Ipc_private, Memory_size, ipc_creat|06 (Shmid = =-1) {perror ("Shmget error"); return-1;} PID = fork (), if (PID = = 0) {addr = (char*) shmat (Shmid, NULL, 0), if (int) addr = = 1) {perror ("Shmat addr Error"); return-1;} strcpy (addr, "I am the Child process\n"); Shmdt (addr); return 3;} else if (PID > 0) {wpid = Waitpid (PID, &status, 0); if (wpid > 0 && wifexited (status)) {printf ("Child proce SS return is%d\n ", Wexitstatus (status));} Failed = Shmctl (Shmid, Ipc_stat, &buf); if (failed = =-1) {perror ("Chmctl error"); return-1;} printf ("Shm_segsz =%d bytes\n",BUF.SHM_SEGSZ);        printf ("parent pid=%d, shm_cpid =%d \ n", Getpid (), buf.shm_cpid); printf ("Chlid pid=%d, shm_lpid =%d \ n", PID, Buf.shm_lpid);p rintf ("mode =%08x \ n", buf.shm_perm.mode); addr = (char*) Shma T (Shmid, NULL, 0), if (int) addr = =-1) {perror ("Shmat addr Error"); return-1;} printf ("%s", addr); Shmdt (addr); Shmctl (Shmid, Ipc_rmid, NULL);} else {perror ("fork Error"); Shmctl (Shmid, Ipc_rmid, NULL); return-1;} return 0;}


Not finished

adjourned

Reference:

http://blog.csdn.net/guoping16/article/details/6584058



Shared memory of process communication

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.