Shared memory
Shared memory is the consent of two unrelated processes to access the same logical memory. Shared memory is a very efficient way to share and pass data between two executing 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 addresses in shared memory. It is 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, which means. Before the first process ends a write to the shared memory, there is no proactive mechanism to prevent the second process from starting to read it.
Therefore, 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, assuming the value of key is 0. With the IPC_PRIVATE flag set in the SHMFLG, the same will create a new piece of shared memory.
In the IPC communication mode, either Message Queuing or shared memory is used. Even the semaphore, each IPC object has a unique name. Called "Keys" (key).
By "Key". The process can identify the object being used. The relationship of the "key" to the IPC object is as if the file name is referred to the file, through the file name. Processes can read and write data within a file, and even multiple processes can share a single file. And in the IPC communication mode. The use of "keys" also enables an IPC object to be shared by multiple processes.
All of the data structures in the Linux system that represent the IPC objects in System V include a ipc_perm structure. This includes the key values for the IPC object. This key is used to find the reference identifier of the IPC object in System V.
Assuming that the "key" is not used, 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 pre-contract a unique key value with other programs, but it's 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. Such The operating system ignores the key, establishes a new shared memory, and specifies a key value. This shared memory IPC identifier ID is then returned.
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 of the memory allocation operations are in page units. So assuming that a process simply applies for only one 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) so the newly created shared memory size is actually the page size that is adjusted from the size of this parameter. That is, assuming that 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.
It effectively contains Ipc_creat and IPC_EXCL, which are functionally equivalent to the o_creat and o_excl of Open ().
Ipc_creat if 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 occurs.
assume that the Ipc_creat,shmget () function is used alone to either return an operator with an existing shared memory, or to return an identifier for the newly created shared memory. Assuming that the ipc_creat and IPC_EXCL flags are used together, Shmget () returns an identifier for the newly created shared memory. Assume that the shared memory already exists, or return-1. The IPC_EXEL flag itself does not make much sense, but with the IPC_CREAT flag it is used to guarantee that the resulting object is new. Instead of 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. and (Shm_r>6) and (SHM_W>6) are global read and write licenses. The
return value
-----------------------------------------------
Returns the identifier of the shared memory successfully. Failed to return -1,errno storage error reason.
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 shared memory value (Shmall) that the system has agreed to establish.
The shared memory referred to by ENOENT key does not exist, and the number of references 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. You can then access the same as in your local space.
-----------------------------------------------
Shmid the shared memory identifier. The ID returned by the Shmget function
SHMADDR pointing shared memory out of the current process memory address where it is directly specified as NULL. Have the kernel decide for itself
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. Error reason exists in error
Note: After fork, the child process inherits the connected shared memory address.
After exec, the child process is detached from the shared memory address itself.
After the process has ended. The connected shared memory address will be detached on its own initiative.
Error code
-----------------------------------------------
Eacces: No permissions have been specified to connect shared memory
EINVAL: Invalid number of references 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. Prevent this process from visiting this piece of shared memory.
SHMADDR: The starting address of the connected shared memory
return value
-----------------------------------------------
Successful return 0
Error returns-1. Error reason exists in error
Note: This function call does not delete the specified shared memory area. Instead of just using the Shmat function to connect (attach) good shared memory out (detach) the current process
Error code
-----------------------------------------------
EINVAL: Invalid number of references 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. Refer to the contributing memory core structure Definition section for detailed instructions.
return value
-----------------------------------------------
Successful return 0
Error returned-1, the cause of errors exists in error
Error code
-----------------------------------------------
eaccess: The parameter cmd is ipc_stat and does not have permission to read the shared memory
Efault: Reference buf point to invalid memory address
EIDRM: Shared memory with identifier Msqid has been deleted
EINVAL: Invalid number of parameters cmd or Shmid
Eperm: The parameter cmd is Ipc_set or ipc_rmid, but does not have sufficient permissions to run
Finally, here's an 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
References:
http://blog.csdn.net/guoping16/article/details/6584058
Shared memory of process communication