IPC (SYSTEMV) shared memory

Source: Internet
Author: User

For a long time I have only been able to smell the name, and have not seen its shape. Finally, in this system of learning Linux programming access to shared memory. Sure enough.

In the previous article we talked about the semaphore, the personal feeling, strictly speaking, the signal volume is only the auxiliary of the city communication. and shared memory really implements process communication.

The shared memory mechanism allows two processes that do not want to shut down to access the same piece of physical memory, which is, of course, a host.

Header file <sys/shm.h> as in the case of semaphores, it is also necessary to include sys/types.h and sys/ipc.h. Of course it's probably already included in the sys/shm.h.

The shared memory functions are as follows:

int Shmget (key_t key, size_t size, int shm_flg);

void * Shmat (int shm_id, void * addr, int shmflg);

int SHMDT (const void * addr);

int shmctl (int shm_id, int command, struct shmid_ds *buf);

In fact, the functions of the IPC series are similar in many places.

Shmget creates a unique token for shared memory by specifying a unique key. The size specifies the amount of shared memory. SHM_FLG specifies permissions and actions. The lower nine bits are the permissions, the other bits are desirable ipc_creat ipc_excl. Of course, key can also be ipc_ PRIVATE, which means that a share can be specified as internal to the process. If you specify Ipc_creat, then if the shared memory already exists, then if IPC_EXCL is specified, an error occurs when the shared memory is present.

The return value of Shmget, which returns the token of shared memory when successful, fails to return 1


Shmat allocates a real available physical memory for shared memory and returns a pointer to that memory. The first parameter, shm_id, is the return value of Shmget, and the second parameter addr, specifying the address of the physical memory. If empty, is assigned by the system. The third parameter specifies the permissions of the process to this physical memory. Common permissions include Shm_rnd, which is typically used when the second parameter is specified by the user. Shm_rdonly, the current process has only read access to physical memory. If you want to write to shared memory, specify this parameter as 0. That is, it is not read-only to write.

The return value of the Shmat returns a pointer to the physical memory if it succeeds and returns null if it fails.


SHMDT in front of us can be understood as attach, that is, binding. This function performs the opposite of shmat---unbind, i.e. Dettach. If the process calls this function, the physical memory can no longer be accessed by using the shared memory token.

The return value of SHMDT, when success is returned 0, fails to return-1.


Shmctl Each IPC has such a function, which is used to understand the real-time IPC state, set the IPC value, and clean up the IPC. The first parameter is also a token of shared memory. The second parameter specifies the action to take on the shared memory. The third parameter determines which fields are filled according to the action of the second parameter. Generally speaking , the most common use of this function is to delete shared memory.

Shmctl return value, success is return 0, failure returns-1.


With these four functions in hand, let's design a small scene. For example, an old man left a fortune of 100 yuan before he died, but three brothers were not allowed to score, but when the three brothers needed money, they could come and get it. Of course, the three brothers can not conflict. You may lose the money. Let's try to realize this scenario.

Well, it's also a similar problem with semaphores. I made a mistake again. Summarize the problems you have encountered in writing.

1. I called the shmctl too early, so that other processes were not getting the content that I had stored in the shared memory. That is, shmctl must be able to use the shared memory in all processes. My own oolong.

2. In general, it is not necessary to use the IPC_EXCL tag, because if it exists, it is created if it does not exist.

3. Same as the peer user, if root creates shared memory, and with ordinary users to try to modify, will certainly report permissions issues.

The code is as follows:

Father.c

#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include < errno.h> #include <sys/shm.h> #define MY_LEGACY 100#define maxlen 10int Main (int argc, char * * argv) {    int ret;    int shmid;    int *legacy = NULL;    Shmid = Shmget ((key_t) 123456, 4, 0666 | Ipc_creat);    if (Shmid < 0)    {        perror ("Oh, I am not die\n");        Exit (exit_failure);    }    Legacy = (int *) Shmat (shmid, NULL, 0);    if (NULL = = Legacy)    {        perror ("\ n");        Exit (exit_failure);    }    *legacy = my_legacy;    printf ("My legacy%d is up to you\n", *legacy);    SHMDT (Legacy);//    Shmctl (Shmid, Ipc_rmid, NULL);    return 0;}
The thing that Lao Tzu does is to save money. For his son to splurge.

Son.c

#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include < errno.h> #include <time.h> #include <sys/shm.h> #include <sys/sem.h>union semun {int VA    L    /* Value for Setval */struct SEMID_DS *buf;  /* Buffer for Ipc_stat, Ipc_set */unsigned short *array;  /* Array for GETALL, SETALL */struct seminfo *__buf; /* Buffer for Ipc_info (linux-specific) */};int main (int argc, char * * argv) {if (ARGC & Lt        2) {printf ("Usage:which son of the poor old Man are\n");    return 0;    } int ret;    int cost = 1;    int shmid;    int *legacy = NULL;    int semid;    struct SEMBUF sem_p;    struct SEMBUF sem_v;    Union Semun Sem_un; Semid = Semget ((key_t) 123456789, 1, 0666 |    Ipc_creat);        if (Semid < 0) {perror ("\ n");    Exit (Exit_failure);    } sem_un.val = 1;    ret = semctl (semid, 0, Setval, Sem_un); Sem_p.sem_num = 0;    Sem_p.sem_op =-1;    SEM_P.SEM_FLG = Sem_undo;    Sem_v.sem_num = 0;    Sem_v.sem_op = 1;    SEM_V.SEM_FLG = Sem_undo; Shmid = Shmget ((key_t) 123456, 4, 0666|    Ipc_creat);        if (Shmid < 0) {perror ("\ n");    Exit (Exit_failure);    } Srand (Time (NULL));    Legacy = (int *) Shmat (shmid, NULL, 0);        while (cost) {Semop (Semid, &sem_p, 1);        if (*legacy <= 0) {break;            } else {int spend = rand ()% 10;            *legacy = *legacy-spend;        printf ("Son%s has spend%d, left%d \ n", argv[1], spend, *legacy);        } sleep (1);    Semop (Semid, &sem_v, 1);    } shmdt ((void*) legacy);    Shmctl (Shmid, Ipc_rmid, NULL); return 0;}
The son is really not good to fight to spend my money. Banks are afraid of problems, so they use semaphores to maintain order.

Look at the results of the operation:

First of all, I save money:

Then the son spends money:

Alas, this is a bit of a problem, this worthless son overdrawn. The main use of the random number, so if the judge currently has five dollars, this is greater than 0, but if the random number generated 10, will naturally overdraft 5. I won't change it. Students in the process of learning or should be on the ground to tap the code to deepen the impression, If you can imagine a scene and then realize it, I believe the effect will be better. This article is the basis of some of the introduction, I hope to help you.

IPC (SYSTEMV) 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.