Linux inter-process communication-Using shared memory

Source: Internet
Author: User
Tags semaphore

One, what is shared memoryshared memory, as the name implies, 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.
Special Reminder : Shared memory does not provide a synchronization mechanism, that is, there is no automatic mechanism to prevent the second process from reading the shared memory until the first process finishes writing it. So we usually need to use other mechanisms to synchronize access to shared memory, such as the amount of semaphores mentioned earlier. For more information on semaphores, you can check out my other article:Linux interprocess communication-using semaphores
second, the sharing of memory makesAs with semaphores, a set of function interfaces is provided in Linux for use with shared memory, and interfaces with shared coexistence are very similar to semaphores and are simpler than interfaces that use semaphores. They are declared in the header file sys/shm.h.
1. Shmget functionThis function is used to create shared memory, which is prototyped as:
int Shmget (key_t key, size_t size, int shmflg);  

first parameter, like the Semget function of semaphores, the program needs to provide a parameter key (not a 0 integer), which effectively names the shared memory segment, and returns a shared memory identifier (non-negative integer) associated with key when the Shmget function succeeds, for subsequent shared memory functions. The call failed to return -1.
Unrelated processes can access the same shared memory through the return value of the function, which represents a resource that the program may want to use, and the program accesses all shared memory indirectly, first by calling the Shmget function and providing a key. A corresponding shared memory identifier (the return value of the Shmget function) is generated by the system, and only the Shmget function uses the semaphore key directly, and all other semaphore functions use the semaphore identifier returned by the Semget function.
The second parameter , size specifies the amount of memory that needs to be shared in bytes
The third parameter , SHMFLG, is the permission flag, which functions like the mode parameter of the Open function, and can be done or manipulated with ipc_creat if it is to be created if the shared memory identified by the key does not exist. The permission flags for shared memory are the same as the read and write permissions for a file, for example, 0644, which means that shared memory that is allowed to be created by a process is read and written to shared memory by processes owned by the memory creator, while processes created by other users can read only shared memory.
2. Shmat functionwhen the shared memory is created for the first time, it cannot be accessed by any process, and the Shmat function is used to initiate access to the shared memory and to connect the shared memory to the address space of the current process. Its prototype is as follows:
void *shmat (int shm_id, const void *shm_addr, int shmflg);  


The first parameter, shm_id, is the shared memory identity returned by the Shmget function. The second parameter, SHM_ADDR, specifies that the shared memory is connected to the address location in the current process, which is usually empty, indicating that the system chooses the address of the shared memory. The third parameter, SHM_FLG, is a set of flag bits, typically 0.
when the call succeeds, returns a pointer to the first byte of shared memory if the call fails to return -1.
3. Shmdt functionThis function is used to detach shared memory from the current process. Note that separating shared memory is not removing it, just making that shared memory no longer available to the current process. Its prototype is as follows:
int SHMDT (const void *SHMADDR);


The parameter shmaddr is the address pointer returned by the SHMAT function, returns 0 when the call succeeds, and returns -1 on failure.
4. Shmctl functionlike the Semctl function of semaphores, it is used to control shared memory, and its prototype is as follows:
int shmctl (int shm_id, int command, struct shmid_ds *buf);



first parameter, shm_id is the shared memory identifier returned by the Shmget function.
The second argument , command is the action to take, it can take the following three values:Ipc_stat: Sets the data in the SHMID_DS structure to the current associated value of shared memory, which overwrites the value of Shmid_ds with the current associated value of shared memory. Ipc_set: If the process has sufficient permissions, set the current association value of shared memory to the value given in the SHMID_DS structure
ipc_rmid: Deleting shared memory segments

The third parameter , buf, is a struct pointer that points to the structure of shared memory mode and access permissions. the SHMID_DS structure includes at least the following members:
struct Shmid_ds  {      uid_t shm_perm.uid;      uid_t Shm_perm.gid;      mode_t shm_perm.mode;  };  

test Case Source code:
#include <sys/stat.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h># Include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #define PERM s_ irusr| S_iwusrint Main (int argc,char **argv) {int Shmid;char *p_addr,*c_addr;if (argc!=2) {fprintf (stderr, "usage:%s\n\a", argv [0]); Exit (1);} if ((Shmid=shmget (ipc_private,1024,perm)) ==-1) {fprintf (stderr, "Create Share Memory error:%s\n\a", Strerror (errno)); Exit (1);} if (fork ()) {p_addr = Shmat (shmid,0,0); memset (p_addr, '//printf ', 1024x768); argv= ("the" [] (]%s\n argv[1), strncpy (p_addr,argv[) 1],1024); wait (NULL); exit (0);} Else{sleep (1); C_addr=shmat (shmid,0,0);p rintf ("Client get%s\n", c_addr); exit (0);} return 1;} </span>

Post-compilation output:Client Get 12345

v. Advantages and disadvantages of using shared memory1, advantages: we can see the use of shared memory for interprocess communication is really convenient, and the interface of the function is also simple, data sharing also makes the data between processes not to transmit, but directly access memory, but also speed up the efficiency of the program. At the same time, it does not require a certain parent-child relationship as the process of communicating with anonymous pipelines.
2, Disadvantage: Shared memory does not provide a mechanism for synchronization, which allows us to use shared memory for interprocess communication, often with the help of other means of synchronization between processes.

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.