Linux shared memory inter-process communication

1. Features:
  1) Shared memory is one of the most efficient inter-process communication, a process can read and write directly to memory, without the need for any data copying. When such pipes after a kernel space created, the user need spatial memory copy, the data needs to be copied, it is inefficient.

  2) To exchange information between multiple processes, kernel set aside a piece of memory area can be accessed by the process needs to be mapped to its own private address space

  3) This process can directly read and write memory area without the need to copy data, thus greatly improving efficiency.

  4) Since the period of the plurality of process shared memory, and therefore we need to rely on some sort of synchronization, such as mutexes and semaphores

 

2. Shared memory usage steps:

  1) Create / open shared memory

  2) mapping shared memory. That is to map the specified shared memory into the process address space for access

  3) revocation of shared memory mapping

  4) delete the shared memory object

3. Related functions:

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

    Function: generating a unique key value

    Parameters: name and can access the file already exists: Pathname

       Proj_id: a character (since only the lower 8 bits) numbers, the key generation, can not be 0

    Return Value: Success: key value; failed: -1

  2)int shmget(key_t key,  size_t size,  int shmflg);

    Function: Create or open shared memory object

    Parameters: key key; the size of the size of shared memory; shmflg IPC_CREAT | IPC_EXCL | 0777 (flag, whether new construction, and permissions)

    Return Value: Successful the shmid (ID shared memory);  Error -1

  3)void *shmat(int shmid, const void *shmaddr,  int shmflg);

    Function: Mapping shared memory that is mapped to the specified shared memory address space of the process for accessing

    Parameters: the shmid shared memory id number; typically by shmaddr NULL, indicating that mapping is done automatically by the system, if not NULL, then the user has specified

             shmflg: SHM_RDONLY the current process is the shared memory can only be read 0 readable and writable

    Return Value: Success: after completion of the address mapping, error: Address -1

    Usage: (p = (char *) shmat (shmid, NULL, 0)) == (char *) - 1 (-1 to turn into strong character address)

  4)int shmdt(const void *shmaddr);

    Function: unmap

    Parameters: To cancel address

    Return Value: 0 success; failure -1

  5)int shmctl(int shmid,  int cmd,  struct shmid_ds *buf);

    :( delete function shared memory) of shared memory for various operations

    : Parameter id number shmid shared memory;  cmd IPC_STAT shmid obtained attribute information stored in the third parameter

          IPC_SET set shmid property information, property to be set on the third parameter

          IPC_RMID: Delete shared memory, this time to the third argument is NULL

    Returns: 0 Success;  failure -1

    用法:shmctl(shmid,IPC_RMID,NULL);

supplement:

1, IPC objects after there has been created, deleted until it is displayed, and the last process you want to remove IPC objects

2, each IPC objects in addition there are also key ID value associated with (property of IPC objects), the role of key values by key values, different processes can open the same IPC objects to find, because after IPC objects created his ID is randomly assigned, only create objects IPC process can directly get the ID, other processes that do not know the ID, and other processes to go through to get this ID key, open the same object through the IPC key. value of 0 indicates private key. Different processes with ftok function, the key value to be generated as a function of ftok and parameters will remain the same.

example:

By a terminal input information written into the shared memory, and print sharing memory data

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

int main(int argc, const char *argv[])
{
    key_t key; //共享内存的唯一标识 key 值
    int shmid; //
    char *p = NULL;

    //  函数原型  key_t ftok(const char *pathname, int proj_id);;
    key = ftok("./app",'a'); //创建key值
    if(key < 0)
    {
        perror("fail ftok ");
        exit(1);
    }//共享内存 不存在,创建
    shmid = shmget(key,128,IPC_CREAT|IPC_EXCL|0777);// 创建/打开共享内存,返回id根据id映射
    if(shmid < 0) 
    {
        if(errno == EEXIST)//文件存在时,直接打开文件获取shmid
        {
            printf("file eexist");
            shmid = shmget(key,128,0777); //如果创建了,直接打开
        }
        else
        {
            perror("shmget fail ");
            exit(1);
        }
    }
    p = (char *)shmat(shmid,NULL,0);//映射,返回地址,根据地址操作,错误 返回 -1 的地址
    if( p == (char *)(-1) ) //错误形式判断
    {
        perror("shmat fail ");
        exit(1);
    }

    read(0,p,10);//从终端读数据,写入p指向的空间
    printf("%s\n",p); //打印p指向空间的内容

    shmdt(p);//解除映射

    //int shmctl(int shmid, int cmd, struct shmid_ds *buf);
    shmctl(shmid,IPC_RMID,NULL); //删除

    return 0;
}

测试:终端输入123 写入共享内存中,然后通过共享内存打印出来



 

Guess you like

Origin www.cnblogs.com/electronic/p/10945668.html