Interprocess communication Three (shared memory)

Source: Internet
Author: User
Tags int size readable semaphore

1. What is 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.

2. How do I use shared memory?

2.1 Allocates a memory area to a process/thread using Shmget (). (process uses Shmget to request a shared memory)
2.2 Use Shmat () to place one or more processes/threads in shared memory, or you can use SHMCTL () to get information or to control shared areas. (Gets the address of the shared memory in this thread)
2.3 Use SHMDT () to detach from the shared area.
2.4 deallocate space using Shmctl ()

2.1shmget ()

#include <sys/types.h>;
#include <sys/ipc.h>;
#include <sys/shm.h>;
int Shmget (KEY,SIZE,SHMFLG)
key_t key;
int SIZE,SHMFLG;

The first parameter, like the Semget function of the semaphore, requires that the program 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 the 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, in bytes, specifies the amount of memory that needs to be shared. The third parameter, SHMFLG is the permission flag, which functions as the mode parameter of the Open function, and if it is to be created if the shared memory that the key identifies does not exist, it can be done or manipulated with ipc_creat. 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.2shmat function The first time the shared memory is created, it cannot be accessed by any process, and the Shmat function is used to initiate access to the shared memory and connect the shared memory to the address space of the current process. Its prototype is as followsvoid *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. 2.3SHMDT function This 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 followsint 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. The 2.4shmctl function, like the SEMCTL function of semaphores, is used to control shared memory, which is prototyped as follows:int shmctl (int shm_id, int command, struct shmid_ds *buf); The first argument, 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, that is, the value of Shmid_ds is overwritten with 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: Delete the third parameter of the shared memory segment, BUF is a structure pointer to the structure of shared memory mode and access rights 3. Instance// Shmread.c

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/shm.h>
#include "Shmdata.h"

int main ()
{
int running = Flag 1;//Whether the program continues to run
void *shm = null;//The original first address of the shared memory allocated
struct Shared_use_st *shared;//point to SHM
int shmid;//Shared Memory identifier
Shmid = Shmget ((key_t) 1234, sizeof (struct shared_use_st), 0666|   Ipc_creat); Create shared memory if (Shmid = =-1)
{
fprintf (stderr, "Shmget failed\n");
Exit (Exit_failure);
}

SHM = Shmat (shmid, 0, 0); Connect shared memory to the address space of the current process
if (SHM = = (void*)-1)
{
fprintf (stderr, "Shmat failed\n");
Exit (Exit_failure);
}
printf ("\nmemory attached at%x\n", (int) SHM);
Set up shared memory
shared = (struct shared_use_st*) SHM;
Shared->written = 0;
while (running)//read data in shared memory
{
There is no process to set data to shared memory to have data readable
if (Shared->written! = 0)
{
printf ("You wrote:%s", shared->text);
Sleep (rand ()% 3);
After reading the data, set written to make the shared memory segment writable
Shared->written = 0;
Input end, exit loop (program)

if (strncmp (Shared->text, "End", 3) = = 0)
running = 0;
}
else//There are other processes in writing data that cannot read data
Sleep (1);
}
Separating 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);
}

Shmwrite.c

#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];//to hold 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 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
Sharer = (struct shared_use_st*) SHM;
while (running)//writes data to shared memory
{
//data has not been read, waits for data to be read, cannot write text to shared memory
while (Shared->written = = 1 )
{
Sleep (1);
printf ("waiting...\n");
}
//write data to shared memory

printf ("Enter some text:");
Fgets (buffer, bufsiz, stdin);
strncpy (shared->text, buffer, TEXT_SZ);
After writing the data, set the written to make the shared memory segment readable
Shared->written = 1;
Input end, exit loop (program)
if (strncmp (buffer, "End", 3) = = 0)
running = 0;
}
Separating shared memory from the current process
if (SHMDT (SHM) = =-1)
{
fprintf (stderr, "Shmdt failed\n");
Exit (Exit_failure);
}
Sleep (2);
Exit (exit_success);

}

Shmdata.h

#ifndef _shmdata_h_header
#define _shmdata_h_header

#define TEXT_SZ 2048

struct SHARED_USE_ST
{
int written;//as a flag, non 0: readable, 0 indicates writable
Char text[text_sz];//record written and read text
};

#endif

Program Compile and run

[[email protected] sharememery] $ls
Shmdata.h SHMREAD.C shmwrite.c

[[email protected] sharememery] $GCC Shmread.c-o Read
[[email protected] sharememery] $GCC Shmwrite.c-o Write
[[email protected] sharememery] $ls
Read Shmdata.h shmread.c shmwrite.c write


Run Write on Console1

[Email protected] Sharememery]$./write
Memory attached at b77c0000
Enter some Text:hello share memery!
Waiting ...
Waiting ...
Enter some text:have a good day!
Waiting ...
Waiting ...
Enter some Text:end
[Email protected] sharememery]$

Run Read on Console2

[Email protected] Sharememery]$./read

Memory attached at b76fa000
You Wrote:hello share memery!
You wrote:have a good day!
You wrote:end
[Email protected] sharememery]$

Interprocess communication Three (shared memory)

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.