Linux Programming-Shared Memory (chapter 14th)

Source: Internet
Author: User
Tags function prototype stdin

14.2 Shared Memory shared Memory is the second of 3 IPC mechanisms that allows two unrelated processes to access the same logical memory.Shared memory is a very efficient way to pass data between two running processes. Most of the shared memory specifically, the memory shared between different processes is scheduled to be the same piece of physical memory.
Shared memory is a special address access created by the IPC for a process that will appear in the address space of the process, and other processes can connect the same piece of shared memory to their own address space. All processes can access addresses in shared memory, As if they were allocated by malloc. If a process writes data to shared memory, the changes are immediately visible to other processes that have access to the same piece of shared memory.
Shared memory provides an effective way to share and pass data between multiple processes. Because it does not provide a synchronization mechanism, it is often necessary to use other mechanisms to synchronize access to shared memory. It is common to use shared memory to provide effective access to large chunks of memory, and to synchronize access to that memory by passing small messages.
There is no automatic mechanism to prevent the second process from starting to read its process until the first process finishes writing to the shared memory. Synchronization control of shared memory access must be the responsibility of the programmer.
shared memory uses functions similar to semaphore functions, and their definitions are defined as follows:
#include <sys/shm.h>
void *shmat (int shm_id, const void *shm_addr, int shmflg);
int shmctl (int shm_id, int cmd, struct shmid_ds *buf);
int SHMDT (const void *SHM_ADDR);
int Shmget (key_t key, size_t size, int shmflg);

As in the case of semaphores, header files Sys/types.h and sys/ipc.h are usually shm.h automatically included in the program.
14.2.1 shmget function function ActionThe Shmget function is used to create shared memory
function prototype int shmget (key_t key, size_t size, int shmflg);
The first parameter of the function parameter, key, effectively names the shared memory segment.
The second parameter, size, specifies the amount of memory that needs to be shared in bytes
The third parameter, SHMFLG, contains the 9-bit permission flags, which work the same as the mode flag used when creating the file. A special bit defined by ipc_creat must and permission flags bitwise OR to create a new shared memory segment.
Permission flags are useful for shared memory because they allow a process to create shared memory that can be written to by a process owned by the creator of the shared memory, while processes created by other users can read only that shared memory. This function is used to provide a valid read-only access to the data. By putting data into shared memory and setting its permissions, you can prevent data from being modified by other users.
function return value If successful, returns a shared memory identifier (which will be used for subsequent shared memory functions). If it fails, it returns-1
14.2.2 Shmat function function ActionThe first time the shared memory is created (the Shmget function is created), it cannot be accessed by any process. To enable access to this shared memory, you must connect it to the address space of a process, which is done by the Shmat function.
function prototype void *shmat (int shm_id, const void *shm_addr, int shmflg);
Function arguments The first parameter shm_id is the shared memory identifier 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, usually a null pointer, which means that the system is allowed to select the address where the shared memory appears.
The third parameter, SHMFLG, is a set of bit flags. Its two possible values are SHM_RND (this flag is used in conjunction with SHM_ADDR to control the address of the shared memory connection) and shm_rdonly (it makes the connected memory read-only). Rarely need to control the address of a shared memory connection, It is common for the system to choose an address, otherwise the application will be too dependent on the hardware.
function return value If successful, a pointer to the first byte of shared memory is returned. If it fails, it returns-1.
Read and Write permissions for shared memory are owned by its owner (the creator of the shared memory), its access rights, and the owner of the current process. Access to shared memory is similar to the access rights of a file.
An exception to this rule is that when shmflg&shm_rdonly is true, it cannot be written even if the access permission for the shared memory allows a write operation.
14.2.3 SHMDT function function ActionThe role of the SHMDT function is to detach shared memory from the current process
function prototype int SHMDT (const void *SHM_ADDR);
The first parameter of a function parameter is a pointer returned by the Shmat function.
The return value of the function returns 0 if successful. Returns 1 if it fails.
Note that separating the shared memory is not removed, only making the shared memory no longer available to the current process.
14.2.4 shmctl function function ActionThe SHMCTL function is used to control shared memory
function prototype int shmctl (int shm_id, int command, struct shmid_ds *buf);
Function arguments The first parameter shm_id is the shared memory identifier returned by Shmget
The second parameter command is the action that will be taken, which can take 3 values, as shown in the following table:
Command description
Ipc_stat sets the data in the SHMID_DS structure to the current associated value of shared memory
Ipc_set if the process has sufficient permissions, set the current association value for shared memory to the value given in the SHMID_DS structure
Ipc_rmid Deleting shared memory segments
The third parameter, buf, is a pointer to the structure SHMID_DS that contains the shared memory mode and access permissions.
The SHMID_DS structure contains at least the following members:
struct Shmid_ds {
uid_t Shm_perm.uid;
uid_t Shm_perm.gid;
mode_t Shm_perm.mode;
};
The return value of the function returns 0 if successful. If it fails, 1 is returned.
Write programs shm1.c and shm2.c.
/************************************************************************* > File name:shm1.c > Description:s HM1.C is Consumer Program > author:liubingbing > Created time:2015 July 18 Saturday 13:07 46 seconds > other:shm1.c ******** /#include <stdio.h> #include <stdlib.h > #include <unistd.h> #include <string.h>/* defines the function used for shared memory */#include <sys/shm.h># Include "shm_com.h" int main () {int running = 1;void *shared_memory = (void*) 0;/* defines a pointer to structure shared_use_st Shared_stuff */ struct Shared_use_st *shared_stuff;int shmid;srand ((unsigned int) getpid ());/* Shmget Create shared memory segment * The first parameter effectively names a shared memory segment * The second parameter specifies the amount of memory that needs to be shared in bytes * The third parameter contains a 9-bit permission flag * If successful, a process identifier (which will be used for subsequent shared memory functions) is returned. If it fails, 1 */shmid = Shmget ((key_t) 1234, sizeof (struct shared_use_st), 0666 | Ipc_creat); if (Shmid = =-1) {fprintf (stderr, "Shmget failed\n"); exit (exit_failure);} /* Shmat function initiates access to shared memory, which connects the shared memory to the address space of a process * The first parameter shmid is the shared memory identity returned by the Shmget functionCharacter * The second parameter specifies that the shared memory is connected to the address location in the current process, usually a null pointer, indicating that the system can select the address where the shared memory appears * The third parameter, a set of bit flags, typically takes 0 * If successful, returns a pointer to the first byte of shared memory. If it fails, return 1 */ Shared_memory = Shmat (Shmid, (void *) 0, 0);/* Determines whether the Shmat function is invoked successfully */if (shared_memory = = (void *)-1) {fprintf (stderr, "Shmat F Ailed\n "); exit (exit_failure);} /* Shared_memory is a pointer to the first byte of shared memory */printf ("Memory attached at%x\n", (int) shared_memory);/* Shared_stuff is a pointer to a struct SHARED_ Use_st pointer, converted it points to shared memory */shared_stuff = (struct Shared_use_st *) shared_memory;/* when data is written to structure Shared_use_st, flags Writen_by_ You inform consumer */shared_stuff->written_by_you = 0;while (running) {if (shared_stuff->written_by_you) {/* if flag Written_ By_you is 1, then output some_text (which in fact means there is new data read into Some_text) */printf ("you wrote:%s", shared_stuff->some_text); Sleep (rand () % 4);/* After outputting some_text data, Written_by_you is set to 0 */shared_stuff->written_by_you = 0;if (strncmp (shared_stuff->some_ Text, "End", 3) = = 0) {running = 0;}}} /* SHMDT function separates shared memory from the current process */if (SHMDT (shared_memory) = = 1) {fprintf (stderr, "Shmdt failed\n"); exit (exit_failure);} /* SHMThe CTL function is used to control shared memory * The first parameter shmid is the shared memory identifier returned by the Shmget function * The second parameter command is the action to be taken, ipc_rmid means to delete the shared memory segment * The third parameter buf is a pointer, It points to the structure that contains the shared memory mode and access rights */if (Shmctl (shmid, ipc_rmid, 0) = =-1) {fprintf (stderr, "Shmctrl (ipc_rmid) failed\n"); Exit (Exit_ FAILURE);} Exit (exit_success);}
Shm2.c
/************************************************************************* > File name:shm2.c > Description:s        HM2.C program is the producer program, through which shm1.c input data to the consumer program > author:liubingbing > Created time:2015 July 18 Saturday 13:40 15 seconds > Other: shm2.c ************************************************************************/#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h>/* sys/shm.h file defines the function used for shared memory */#include <sys/ shm.h> #include "shm_com.h" int main () {int running = 1;void *shared_memory = (void *) 0;/* Shared_stuff is point to Shared_use_ The ST structure pointer * SHARED_USE_ST structure is used in both consumer and producer programs, and when data is written to this structure, Written_by_you notifies the consumer */struct Shared_use_st *shared_stuff;char Buffer[bufsiz];int shmid;/* shmget function for creating shared memory * The first parameter key effectively names the shared memory segment * The second parameter size_t specify the amount of memory that needs to be shared in bytes * The third parameter, SHMFLG, contains a 9-bit permission flag, similar to file access * If successful, returns a nonnegative integer, which is the shared memory identifier. If it fails, 1 */shmid = Shmget ((key_t) 1234, sizeof (struct shared _use_st), 0666 | Ipc_creat);/* Determine if shared memory has been created successfully */if (Shmid = =-1) {fprintf(stderr, "Shmget failed\n"); exit (Exit_failure); /* The Shmat function enables access to shared memory, which connects shared memory to the address space of a process * The first parameter shmid is the shared memory identifier returned by Shmget * The second parameter shm_addr specifies that the shared memory is connected to the address location in the current process, usually a null pointer, Represents an address that allows the system to select shared Memory * The third parameter, SHMFLG, is a set of bit flags * If successful, a pointer to the first byte of shared memory is returned. If it fails, 1 */shared_memory = Shmat (Shmid, (void *) 0, 0) ;/* Determines whether the start of access to shared memory is successful */if (shared_memory = = (void *)-1) {fprintf (stderr, "Shmat failed\n"); exit (exit_failure);} /* Shared_memory is a pointer to the first byte of shared memory */printf ("Memory attached at%x\n", (int) shared_memory); Shared_stuff = (struct shared_ Use_st *) Shared_memory;while (running) {/* Determines whether the flag written_by_you is 1, or 1, indicating that the data in Some_text has not been read, the process continues to sleep wait some_ Text is read */while (shared_stuff->written_by_you = = 1) {sleep (1);p rintf ("Waiting for client...\n");} printf ("Enter some text:"); */* reads from the standard input stdin up to bufsiz bytes of data into the in-memory */fgets (buffer, Bufsiz, stdin) that the buffer points to;/* strncpy copies up to TEXT_SZ bytes of data from buffer points to memory */strncpy (Shared_stuff->some_text, Share_stuff->some_text points) buffer, TEXT_SZ);/* Set flag written_by_you to 1 */shared_stuff->wriTten_by_you = 1;/* Determines whether the first three bytes of buffer are "end" */if (strncmp (buffer, "End", 3) = = 0) {running = 0;}} /* SHMDT function detaches shared memory from the current process * parameter Shared_memroy is the address pointer returned by the SHMAT function (access to shared memory enabled) * Returns 0 if successful. If it fails, return 1 * Note that separating shared memory does not remove it. Just make the shared memory no longer available to the current process */if (SHMDT (shared_memory) = = 1) {fprintf (stderr, "Shmdt failed\n"); exit (exit_failure);} Exit (exit_success);}
The first program is the consumer, which creates a shared memory segment and then displays the data written to it.
The second program is the producer, which connects an existing shared memory segment and allows data to be entered into it
.
First create a common header file that defines the shared memory that will be distributed, named Shm_com.h
/************************************************************************* > File Name:    shm_com.h > Description:  shm_com.h define shared memory to be distributed > Author:       liubingbing > Created time:2015 July 18 Saturday 13:02 43 sec > Other:        shm_com.h is used by consumers (SHM1.C) and producer (shm2.c) programs. When data is written to this structure, consumers are notified using the written_by_you in the structure. ******************** /#ifndef _shm_com_h#define _shm_com_h#define TEXT_SZ 2048struct shared_use_st {int Written_by_you;char SOME_TEXT[TEXT_SZ];}; #endif
The structure defined here is used in both consumer and producer programs. When data is written to this structure, an integer flag in the structure is used to written_by_you the consumer. The length of the file that needs to be transferred 2K is arbitrary.
Run the program and get the following results:

Program parsing the first program SHM1 creates a shared memory segment and then connects it to its own address space. A structure shared_use_st is used at the beginning of shared memory. There is a flag in this structure written_by_you, when there is data written in the shared memory, Set this flag to 1. The program reads the text from the shared memory, prints it out, and sets the flag to 0. Use a special string end to exit the loop, and the program detaches the shared memory segment and deletes it.
A second program SHM2 uses the same key 1234来 to obtain and connect to the same shared memory segment, and then it prompts the user to enter the text. If the flag written_by_you is set to 1,SHM2, you know that the customer process has not finished reading the last data, So just keep waiting. When other processes set Written_by_you to 0 o'clock, SHM2 writes new data and sets the flag written_by_you to 0, which also uses the string end to terminate and detach shared memory segments.
Note that the very rudimentary synchronization flag in the program written_by_you it contains a very inefficient busy wait (which keeps looping), which can make the program very simple, but in practical programming, you should use semaphores or pass messages (using pipelines or IPC messages), A method of generating signals to provide a more efficient synchronization mechanism between the application read and write sections.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Linux Programming-Shared Memory (chapter 14th)

Related Article

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.