Linux inter-process communication-using shared memory

Source: Internet
Author: User
The following describes another way of inter-process communication, using shared memory. 1. What is shared memory, as its name implies, is shared memory that allows two unrelated processes to access the same logical memory. Shared Memory is a very effective way to share and transmit data between two running processes. The memory shared by different processes is usually the same physical memory. Processes can connect the same shared memory to their own address space. All processes can access the addresses in the shared memory, as if they were allocated by the malloc function in C language. If a process writes data to the shared memory, the changes immediately affect any other process that can access the same shared memory. Note: the shared memory does not provide a synchronization mechanism. That is to say, there is no automatic mechanism to prevent the second process from reading the shared memory before the write operation of the first process ends. Therefore, we usually need other mechanisms to synchronize access to the shared memory, such as the semaphore mentioned above. For more information about semaphores, see another article: Linux inter-process communication-using semaphores 2. Using shared memory makes it the same as semaphores, in Linux, a set of function interfaces are also provided to use shared memory. The interfaces that use shared coexistence are also very similar to those of semaphores, and are easier to use than semaphores. They are declared in the header file SYS/SHM. h. 1. shmget function this function is used to create shared memory. Its prototype is:
int shmget(key_t key, size_t size, int shmflg);
The first parameter, like the semget function of the semaphore, the program needs to provide a parameter key (non-0 integer), which is effectively named for the shared memory segment, when the shmget function succeeds, a key-related shared memory identifier (non-negative integer) is returned for subsequent shared memory functions. -1. unrelated processes can access the same shared memory through the return value of this function. It represents a resource that the program may use. The program accesses all the shared memory indirectly, the program first calls the shmget function and provides a key, and then the system generates a corresponding shared memory identifier (the return value of the shmget function). Only the shmget function directly uses the semaphore key, all other semaphore functions use the semaphore identifier returned by the semget function. The second parameter, size in bytes, specifies the third parameter of the memory capacity to be shared. shmflg is the permission flag, which serves the same purpose as the mode parameter of the open function, if you want to create the shared memory with the key if it does not exist, you can perform the operation with ipc_creat. The shared memory permission mark is the same as the file read/write permission. For example, 0644, it allows the shared memory created by a process to be read and written to the shared memory by the process owned by the memory creator. At the same time, the process created by other users can only read the shared memory. 2. When the shmat function is created for the first time, it cannot be accessed by any process. The shmat function is used to start access to the shared memory, and 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 identified by the shared memory returned by the shmget function. The second parameter, shm_addr, specifies the location where the shared memory is connected to the address in the current process. It is usually null, indicating that the system will select the address of the shared memory. The third parameter, shm_flg is a set of flags, usually 0. If the call succeeds, a pointer pointing to the first byte of the shared memory is returned. If the call fails, the-1.3 and shmdt functions are returned. This function is used to separate the shared memory from the current process. Note: separating the shared memory is not to delete it, but to make the shared memory no longer available to the current process. Its prototype is as follows:
void *shmat(int shm_id, const void *shm_addr, int shmflg);
The shmaddr parameter is the address pointer returned by the shmat function. If the call is successful, 0 is returned. If the call fails,-1.4 is returned. The shmctl function is the same as the semctl function of the semaphore to control the shared memory. 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 identifier returned by the shmget function. The second parameter, command, is the operation to take. It can take down the following three values: ipc_stat: Set the data in the shmid_ds structure to the current associated value of the shared memory, that is, the shmid_ds value is overwritten by the current associated value of the shared memory. Ipc_set: if the process has sufficient permissions, set the current associated value of the shared memory to the value ipc_rmid in the shmid_ds structure: Delete the third parameter of the shared memory segment, buf is a structure pointer pointing to the structure of the shared memory mode and access permission. 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;};

3. It's time to use shared memory for inter-process communication. The following describes how two unrelated processes communicate with each other through shared memory. One file shmread. c creates the shared memory and reads the information. The other file shmwrite. c writes data to the shared memory. To facilitate operations and unify the data structure, the two files have the same data structure defined in the file shmdata. C. Written in the shared_use_st structure serves as a readable or writable sign. Non-0: Indicates readable, 0 indicates writable, and text indicates files in memory. The source code of shmdata. C is as follows:

# Ifndef _ shmdata_h_header # DEFINE _ shmdata_h_header # define text_sz 2048 struct shared_use_st {int written; // as a flag, non-0 indicates readable, 0 indicates writable char text [text_sz]; // record the written and read text}; # endif
The source code of the source file shmread. C is as follows:
# Include <unistd. h> # include <stdlib. h> # include <stdio. h> # include <sys/SHM. h> # include "shmdata. H "int main () {int running = 1; // void * SHM = NULL indicates whether the program continues to run; // original first address of allocated shared memory struct shared_use_st * shared; // point to shmint shmid; // shared memory identifier // create shared memory shmid = shmget (key_t) 1234, sizeof (struct shared_use_st), 0666 | ipc_creat); If (shmid =-1) {fprintf (stderr, "shmget failed \ n"); exit (exit_failure );} // connect the shared memory to the address space of the current process. SHM = Shmat (shmid, 0, 0); If (SHM = (void *)-1) {fprintf (stderr, "shmat failed \ n"); exit (exit_failure );} printf ("\ nmemory attached at % x \ n", (INT) SHM); // set the shared memory shared = (struct shared_use_st *) SHM; shared-> written = 0; while (running) // read data in the shared memory {// No process has set data to the shared memory. data can be read if (shared-> written! = 0) {printf ("You wrote: % s", shared-> text); sleep (RAND () % 3); // read data, set written to enable the shared memory segment to write shared-> written = 0; // enter the end and exit the loop (Program) if (strncmp (shared-> text, "end", 3) = 0) Running = 0;} else // other processes are writing data and cannot read data sleep (1 );} // detach the shared memory from the current process if (shmdt (SHM) =-1) {fprintf (stderr, "shmdt failed \ n"); exit (exit_failure );} // Delete shared memory if (shmctl (shmid, ipc_rmid, 0) =-1) {fprintf (stderr, "shmctl (ipc_rmid) failed \ n "); exit (exit_failure);} exit (exit_success );}
The source code of the source file shmwrite. C is as follows:
# Include <unistd. h> # include <stdlib. h> # include <stdio. h> # include <string. h> # include <sys/SHM. h> # include "shmdata. H "int main () {int running = 1; void * SHM = NULL; struct shared_use_st * shared = NULL; char buffer [bufsiz + 1]; // used to save the input text int shmid; // create shared memory shmid = shmget (key_t) 1234, sizeof (struct shared_use_st), 0666 | ipc_creat ); if (shmid =-1) {fprintf (stderr, "shmget failed \ n"); exit (exit_failure );} // connect the shared memory to the address space of the current process. SHM = shmat (shmid, (void *) 0, 0); If (SHM = (void *)-1) {fprintf (stderr, "shmat failed \ n"); exit (exit_failure);} printf ("memory attached at % x \ n", (INT) SHM ); // set shared memory shared = (struct shared_use_st *) SHM; while (running) // write data to the shared memory {// The data has not been read, wait for the data to be read. You cannot write the text while (shared-> written = 1) {sleep (1); printf ("waiting... \ n ") ;}// write data to the shared memory printf (" Enter some text: "); fgets (buffer, bufsiz, stdin); strncpy (shared-> text, buffer, text_sz); // After writing data, set written to make the shared memory segment readable shared-> written = 1; // enter the end and exit the loop (Program) if (strncmp (buffer, "end", 3) = 0) Running = 0;} // detach the shared memory from the current process if (shmdt (SHM) =-1) {fprintf (stderr, "shmdt failed \ n"); exit (exit_failure);} Sleep (2); exit (exit_success );}
Let's take a look at the running results: Analysis: 1. The program shmread creates the shared memory and connects it to its own address space. A struct_use_st structure is used at the beginning of the shared memory. There is a written sign in this structure. When other processes in the shared memory write data to it, the written in the shared memory is set to 0, and the program waits. When it is not 0, it indicates that no process writes data to the shared memory, the program reads data from the shared memory and outputs the data, and then resets the setting of written in the shared memory to 0, that is, let the shmwrite process write data. 2. The program shmwrite gets the shared memory and connects it to its own address space. Check whether the written value in the shared memory is 0. If not, it indicates that the data in the shared memory has not been completed. Wait for other processes to complete reading and prompt the user to wait. If the written value of the shared memory is 0, it indicates that no other process reads the shared memory, the user is prompted to enter the text and set the written value in the shared memory to 1 again, indicating that the write is complete, other processes can read shared memory. 4. Security discussions about the previous example this program is insecure. When multiple programs read and write data to the shared memory at the same time, the problem arises. You may think that you can change the written usage mode. For example, a process can write data to the shared memory only when the written is 0, however, a process can only read data when the value of written is not 0. At the same time, it adds written to 1. After reading the data, it performs the minus 1 operation. This is a bit like the read/write lock function in the file lock. It seems to work. However, this is not an atomic operation, so this operation is not feasible. If two processes access the shared memory at the same time when the written value is 0, they will find that the written value is 0, so both processes perform write operations on it, obviously not. When written is 1, two processes perform read operations on the shared memory at the same time. When both processes read the shared memory, written becomes-1. in order for the program to be executed securely, there must be a process synchronization hexadecimal mechanism to ensure that the operation into the critical section is an atomic operation. For example, you can use the semaphore mentioned above to synchronize processes. Because semaphore operations are atomic. 5. advantages and disadvantages of using shared memory 1. Advantages: we can see that it is very convenient to use shared memory for inter-process communication, and the function interface is also simple, data sharing also makes data between processes not transmitted, but directly accesses the memory, which also speeds up program efficiency. At the same time, it does not require a parent-child relationship for processes that communicate like Anonymous pipelines. 2. Disadvantages: shared memory does not provide a synchronization mechanism, which means that we often need to use other means to synchronize data between processes when using shared memory for inter-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.