Fourth Lecture communication between the Linux process standard IPC shared memory

table of Contents

Fourth, the standard IPC

4.1 Shared Memory

4.1.1 concepts and principles

4.1.2 Use


Fourth, the standard IPC

IPC is a kind of follow the standard specified standard IPC (interprocess communication) collectively referred to, in fact, which all have IPC has part of the same standard

Standard IPC comprises a shared memory semaphore message queues set

Universal standard IPC specification (upper: user: kernel), as shown below:

(1) all standard IPC has an internal ID as a unique identifier

(2) obtaining the internal ID ,  you need an external key, type key_t

(3) method to get the key in three ways:

        1, using a macro IPC_PRIVATE as a key, but this way can not get outside, so the basic need

        2, in the code customize all key

        3, using ftok () function to get a key

#include <sys/types.h>
#include <sys/ipc.h>

key_t ftok(const char *pathname, int proj_id);

             parameter:

                    pathname - path (must be valid / or.)

                    proj_id - Engineering ID (non-8-bit data is 0, typically to a character)

                    Successful return key, failure to return -1

 

(4) be acquired by key just get ID , commonly used functions are called xxxget (), for example: shmget () msgget ()

(5) providing a certain standard IPC functions called xxxctl (), this function comprising at least the following functions

         By a function of the parameter to control cmd

            Query ------- IPC_STAT

            Delete ------- IPC_RMID    

            Modify ------- IPC_SET

(6) IPC standard common commands

        ipcs - query the current standard IPC structure of the system

        ipcrm - Delete the current system standard IPC structure (deleted through ID)

            Options:

                  -a all IPC structure

                  -m shared memory

                  -q message queue

                  -s semaphore set

          Mount nattch number of processes

 

4.1 Shared Memory

4.1.1 concepts and principles

Shared memory is one of the standard IPC, its approximate standard as stated before

Its principle is that system takes a physical memory as a medium, the system kernel (MMU) is responsible for management, which allows all the processes of this physical memory mapping, so different processes can access the same piece of physical memory, enabling data alternately

Because fast memory access, the shared memory is the most efficient IPC

However, the multiple processes of physical memory read and write data is likely to cause confusion, require additional protection mechanisms ( using the semaphore set )

 

4.1.2 Use

    1) Get Key , function by ftok

    2) by shmget () Gets / create a shared memory

          

          parameter:

                key - the key step taken

                size - the size of the shared memory (valid when creating)

                shmflg - create identity and entitlement rights (when creating effective)

                IPC_CREAT | 0666

                Successful return ID shared memory , failure to return -1

    3) by the shmat () maps / shared memory mounted

          

         parameter:

               shmid - Shared Memory ID

               shmaddr - target address mappings (chosen by the system to NULL)

               shmflg - mapping identifier (typically to 0, to SHM_RDONLY for read-only)

               The successful return of the mapping destination address , failed to return (void *) - 1

    Shared memory 4) Use

    5) by using shmdt End () unmapped / disengaged shared memory

         

    6) If you no longer use, use shmctl to delete the shared memory (shared memory just to delete a shared memory plus a mark delete, mount, etc. is deleted when the number 0)

        

        parameter:

              shmid - Shared Memory ID

              cmd - command

                    IPC_RMID: Delete

                    IPC_SET: Modify

                    IPC_STAT: get

              Incoming set / get time to / from the shared memory information, following its data type, which can be modified is the uid, gid and mode - buf

              shmctl function returns 0 on success, failure to return -

struct shmid_ds {
               struct ipc_perm shm_perm;    /* Ownership and permissions */
               size_t          shm_segsz;   /* 大小 */
               time_t          shm_atime;   /* 最后挂载(映射)时间*/
               time_t          shm_dtime;   /* 最后卸载(解除映射)时间 */
               time_t          shm_ctime;   /* 最后修改时间*/
               pid_t           shm_cpid;    /* 创建者PID */
               pid_t           shm_lpid;    /* 最后一个挂载/卸载PID */
               shmatt_t        shm_nattch;  /* 当前挂载的进程数*/
               ...
           };
struct ipc_perm {
               key_t          __key;    /* Key*/
               uid_t          uid;      /* Effective UID of owner */
               gid_t          gid;      /* Effective GID of owner */
               uid_t          cuid;     /* Effective UID of creator */
               gid_t          cgid;     /* Effective GID of creator */
               unsigned short mode;     /* 权限 */
               unsigned short __seq;    /* Sequence number */
           };

 

 

The following code, the process to create the shared memory and maps it to its own process space, use it again, and finally lift the map:

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

int main()
{
    //1.获取key
    key_t key = ftok(".",'x');
    if(key==-1){
        perror("ftok");
        exit(-1);
    }

    //2.创建共享内存
    int shmid = shmget(key,10,IPC_CREAT|0666);
    if(shmid==-1){
        perror("shmget");
        exit(-1);
    }

    //3.映射共享内存
    void *p = shmat(shmid,0,0);
    if(p==(void *)-1){
        perror("shmat");
        exit(-1);
    }

    //4.使用共享内存
    *(int *)p = 100;

    //5.解除映射
    shmdt(p);

    return 0;
}

Communicate together with it the following code to get the key to this process is consistent in order to obtain the same shared memory ID, and map them using this ID, and then use it, and finally to remove shared memory:

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

int main()
{
    //1.获取key
    key_t key = ftok(".",'x');
    if(key==-1){
        perror("ftok");
        exit(-1);
    }

    //2.获取共享内存
    int shmid = shmget(key,0,0);
    if(shmid==-1){
        perror("shmget");
        exit(-1);
    }

    //3.映射共享内存
    void *p = shmat(shmid,0,0);
    if(p==(void *)-1){
        perror("shmat");
        exit(-1);
    }

    //4.使用共享内存
    printf("data = %d\n",*(int *)p);

    //5.解除映射
    shmdt(p);

    //6.不再使用删除共享内存
    shmctl(shmid,IPC_RMID,0);

    return 0;
}

However, this is not standard!

If for the same resource, a process to write it, read it and at the same time another process

This will be chaos !!!

Thus creating mutual exclusion and synchronization process (in my blog semaphore set has to speak)

 

Published 52 original articles · won praise 40 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_40519315/article/details/104210920