Linux inter-process communication shared memory

Source: Internet
Author: User

The process can read and write memory directly without any data replication. To exchange data between multiple processes
Information, the kernel sets aside a memory area, which can be mapped by the process to be accessed
To its own private address space, the process directly reads and writes this memory area without the need for data
To improve the efficiency. Because multiple processes share the memory, the synchronization mechanism is required, as shown in figure
Mutex lock and semaphore.

The implementation of shared memory is divided into three steps:

1. Create shared memory, shmget ()
Shmget (create or enable shared memory)
Header file # include <sys/IPC. h>
# Include <sys/SHM. h>
The function defines int shmget (key_t key, size_t size, int shmflg );
Function Description key: the return value of ipc_private or ftok, ID of the identifier
Size: the size of the shared memory area. Shmflg: The permission bit of the open function. It can also be expressed in octal notation.
Returned value: Memory identifier returned successfully.-1 is returned if an error occurs.
# Define ipc_creat01000
/* Create key if key does not exist .*/
# Define ipc_excl02000
/* Fail if key exists .*/
# Define ipc_nowait04000
/* Return Error on wait .*/
2. Map the shared memory to map the created shared memory to the specific process space. shmat ()
Shmat (ing shared memory)
Header file # include <sys/types. h>
# Include <sys/SHM. h>
Function Definition void * shmat (INT shmid, const void * shmaddr, int shmflg );

Function Description shmid: The identifier of the shared memory area to be mapped.
Shmaddr: maps the shared memory to the specified address (if it is null, the system automatically completes the ing)
Shmflg: shm_rdonly: Shared Memory read-only. The default value is 0. The shared memory can be read and written.
Returned value: address after successful ing. Error:-1
3. Undo the Shing shmdt ()
Shmdt (the shared memory is separated from the process)
Header file: # include <sys/types. h>
# Include <sys/SHM. h>
Function Syntax: int shmdt (const void * shmaddr );
Function Description: shmaddr: Address mapped after shared memory
Returned value: Success 0, error-1
Case: create a shared memory zone, and then create a sub-process to share the memory in the parent and child processes.
Map to their respective address spaces
The parent process waits for user input, and then writes the string entered by the user to the shared memory.
The wrote string written in the memory header indicates that the process has successfully written data. Sub-process waits until sharing
The header string of the memory is wrote, and then the valid data of the shared memory (the string entered by the user in the parent process)
Print on the screen. After the Parent and Child processes are working, the Mappings with the shared memory are removed.
Synchronize parent and child with a flag string
Command IPCS is used to report the status of inter-process communication mechanisms. It can view shared memory and message queues.
And other inter-process communication mechanisms, using the system () function to call the shell command IPCS

Sem_com.h ## ifndef _ sem_com_h __# DEFINE _ sem_com_h _/*** function call interfaces related to semaphores are complex. They are encapsulated into several basic functions of a single * semaphore of two dimensions. * Semaphores initialization function init_sem () * P operation plus sem_p () * V Operation minus sem_v () * remove semaphores del_sem () */# include <sys/types. h> # include <sys/IPC. h> # include <sys/SEM. h> Union semun {int Val ;}; extern int init_sem (INT sem_id, int init_value); extern int sem_p (INT sem_id); extern int sem_v (INT sem_id ); extern int del_sem (INT sem_id); # endif ------------------------------------------------------ sem_com.c ---------------------------------------------- ------- # Include "sem_com.h"/** semaphore initialization function */INT init_sem (INT sem_id, int init_value) {Union semun sem_union; sem_union.val = init_value; // init_value is the initial value if (semctl (sem_id, 0, setval, sem_union) =-1) {perror ("initialize semaphore"); Return-1;} return 0 ;} /** function for deleting semaphores from the system */INT del_sem (INT sem_id) {Union semun sem_union; If (semctl (sem_id, 0, ipc_rmid, sem_union) =-1) {perror ("delete semaphore"); Return-1 ;} }/** P operation */INT sem_p (INT sem_id) {struct sembuf sem_ B; sem_ B .sem_num = 0; // The number of a single semaphore should be 0sem_ B .sem_op =-1; // indicates the P operation sem_ B .sem_flg = sem_undo; // The System Automatically releases the residual semaphores in the system if (semop (sem_id, & sem_ B, 1) =-1) {perror ("semop"); Return-1;} return 0;}/** v operation */INT sem_v (INT sem_id) {struct sembuf sem_ B; sem_ B .sem_num = 0; // The number of a single semaphore should be 0sem_ B .sem_op = 1; // indicates the V Operation sem_ B .sem_flg = sem_undo; If (semop (sem_id, & sem_ B, 1) =-1) {perro R ("semop v"); Return-1;} return 0;} ------------------------------------------------------ shmem. c ---------------------------------------------------- # include <sys/types. h> # include <sys/IPC. h> # include <sys/SHM. h> # include <sys/SEM. h> # include <stdio. h> # include <stdlib. h> # include <string. h> # include <unistd. h> # include "sem_com.h" # define buffer_size 2048pid_t PID; int shmid; // The identifier of the shared memory area to be mapped to int Semid; // defines the semaphore Mutex char * shm_addr between processes that implement shared memory; // address mapped to the shared memory char buff [buffer_size]; void function_init () {// create a semaphore Semid = semget (ftok ("/Home", 2), 1, 0666 | ipc_creat); init_sem (Semid, 1 ); // Initial Value: 1 // create shared memory shmid = shmget (ipc_private, buffer_size, 0666); If (shmid <0) {perror ("shmget "); exit (1);} else {printf ("create shard-memory shmid: % d \ n", shmid) ;}} void function_end () {// Delete the semaphore del_sem (Semid); // remove the shared memory ing if (shmdt (shm_addr )) <0) {perror ("shmdt"); exit (1) ;}// Delete shared memory ipc_rmid Delete shared memory segment if (shmctl (shmid, ipc_rmid, null) ==- 1) {perror ("shmctl"); exit (1) ;}else {printf ("delete shared-memory \ n") ;}} int main () {function_init (); pid = fork (); If (pid = 0) {// sub-process // ing shared memory shm_addr = shmat (shmid, null, 0 ); if (shm_addr = (void *)-1) {perror ("Child: shmat"); exit (1) ;}else {do {sem_p (Semid ); printf ("\ nchild: attach shared-memory % P: % s \ n", SH M_addr, shm_addr); If (strncmp (shm_addr, "quit", 4) = 0) {break;} memset (shm_addr, 0, buffer_size); sem_v (Semid );} while (1) ;}// display shared memory // system ("IPCS-M");} else if (pid> 0) {// parent process // ing shared memory shm_addr = shmat (shmid, 0, 0); // The parent process sets the data do {sem_p (Semid) to the shared memory ); // The signal value minus printf ("parent: Enter some text to the shared memory (enter 'quit' to exit): \ n"); If (fgets (buff, buffer_size, stdin) = NULL) {perror ("fgets"); sem_v (S Emid); break;} strncpy (shm_addr, buff, strlen (buff); sem_v (Semid);} while (strncmp (buff, "quit", 4 )! = 0); function_end ();} exit (0);} ----------------------------------------------------- shmem #. /BTS create shard-memory shmid: 1966089 parents: Enter some text to the shared memory (enter 'quit' to exit): Hi child! "Good afternoon" Child: attach shared-memory 0xb78af000: Hi child! "Good afternoon" Parents: Enter some text to the shared memory (enter 'quit' to exit): OK let's gochild: attach shared-memory 0xb78af000: OK let's go parents: Enter some text to the shared memory (enter 'quit' to exit): quitdelete shared-memorychild: attach shared-memory 0xb78af000: Quit

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.