Linux interprocess communication-Shared memory

Source: Internet
Author: User

Shared memory is the most efficient IPC mechanism because it does not involve any data transfer between processes. The problem with this efficiency is that we have to use other assistive means to synchronize the process's access to memory, otherwise it will produce a race condition (which we typically use with semaphores). Therefore, shared memory is typically used in conjunction with other interprocess communication methods.


The Linux shared memory API is defined in the Sys/shm.h header file, including 4 system calls: Shmget, Shmat, SHMDT, and Shmctl

#include <sys/shm.h>int sys_shmget (key_t key, int size, int shmflg), void *shmat (int shmid, const void *SHMADDR, int SHMFLG); int sys_shmdt (char *shmaddr); int shmctl (int shmid,int cmd,struct shmid_ds *buf);

L shmget system calls to create a new shared memory, or to acquire a shared memory that already exists.

Like the Shmget system call, the key parameter is a key value that identifies a globally unique shared memory. The size parameter specifies the amount of the share, in bytes. If you are creating a new shared memory, the size value must be specified. If you are getting shared memory that already exists, you can set the size to 0.

The use and meaning of the SHMFLG parameter is the same as the Semflag parameter of the Semget system call

Shmget returns a positive integer when successful, which is the identifier for the shared memory. Shmget returns 1 on failure, and sets errno. If Shmget is used to create shared memory, all bytes of this shared memory are initialized to 0, and the associated kernel data structure Shmid_ds will be created and initialized.


L Shmat and shmdt are used to correlate/detach shared memory, when shared memory is created/acquired, we cannot immediately access it, we need to associate it to the address space of the process, and then detach it from the address space.

Where the Shmid parameter is the shared memory identifier returned by the Shmget call. The SHMADDR parameter specifies which block of address space the shared memory is associated to the process, and the final effect is affected by the optional flag shm_rnd of the SHMFLG parameter:

If SHMADDR is null, the associated address is selected by the operating system. This is the recommended practice to ensure portability.


L Shmctl is used to control some properties of shared memory, andtheshmid parameter is The shared memory identifier returned by the Shmget call. the cmd parameter specifies the command to execute. The return value of Shmctl succeeds depends on the cmd parameter, returns 1On Failure, and sets the errno .


Shared Memory Program Examples

#include <sys/sem.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include < sys/wait.h> #define ERR_SYS (msg) do {perror (msg); exit ( -1),} while (0) union semun{int val;struct Semid_ds *buf;unsigne d Short int *array;struct seminfo * __BUF;};  void PV (int sem_id, int op) {struct Sembuf sem_b;sem_b.sem_num = 0;sem_b.sem_op = OP;SEM_B.SEM_FLG = Sem_undo;semop (sem_id, &sem_b, 1);} int main (void) {int sem_id = Semget (ipc_private, 1, 0666); int shm_id = Shmget (Ipc_private, 4, 0666); Union Semun Sem_un;sem_ Un.val = 1;semctl (sem_id, 0, Setval, sem_un);p id_t pid = fork (), if (PID < 0) Err_sys ("fork"), else if (PID = = 0) {char *SHMP ;p V (sem_id,-1); SHMP = Shmat (shm_id, NULL, 0), if (SHMP = = (char *) ( -1)) Err_sys ("Child Shmat"); * (int *) SHMP = 10;SHMDT (SHMP) ;p rintf ("Child get the SEM and would sleep 2s.\n"); Sleep (2);p V (sem_id, 1); exit (0);} Else{char *shmp;sleep (1);p V (sem_id,-1), SHMP = Shmat (shm_id, NULL, 0), if (SHMP = = (char *) ( -1)) Err_sys ("Child Shmat"); printf ("SHM:%d\n", * (int *) SHMP); Shmdt (SHMP);p rintf (" Parent get the SEM and would sleep 2s.\n "); Sleep (2);p V (sem_id, 1);} WAITPID (PID, NULL, 0), Shmctl (shm_id, Ipc_rmid, null), Semctl (sem_id, 0, Ipc_rmid, sem_un); return 0;}

Reference:

1,"Linux High Performance Server Programming" chapter 13th Multi-process programming/shared memory

2, Linux Inter-process communication-shared memory (this tells the more detailed ...)

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

Linux interprocess communication-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.