linux进程通信之共享内存

共享内存同意两个或多个进程共享一给定的存储区,由于数据不须要来回复制,所以是最快的一种进程间通信机制。共享内存能够通过mmap()映射普通文件(特殊情况下还能够採用匿名映射)机制实现,也能够通过系统V共享内存机制实现。应用接口和原理非常easy,内部机制复杂。为了实现更安全通信,往往还与信号量等同步机制共同使用。以下主要介绍系统V共享内存机制,主要用到的系统API包含:

1.shmget函数:获得一个共享内存标识符。

int shmget(key_t key, size_t size, int flag);

key: 标识符的规则
size:共享存储段的字节数
flag:读写的权限
返回值:成功返回共享存储的id,失败返回-1

2.shmat函数:进程将共享内存连接到它的地址空间。

void *shmat(int shmid, const void *addr, int flag);

shmid:共享存储的id
addr:一般为0,表示连接到由内核选择的第一个可用地址上
flag:如前所述,一般为0        //推荐值
返回值:假设成功,返回共享存储段地址,出错返回-1


3.shmdt函数:将共享内存与进程的地址空间脱轨。

int shmdt(void *addr);

addr:共享存储段的地址,曾经调用shmat时的返回值
shmdt将使相关shmid_ds结构中的shm_nattch计数器值减1


4.shmctl函数:删除该共享内存。

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

shmid:共享存储段的id
cmd:一些命令,有:IPC_STAT,IPC_RMID,SHM_LOCK,SHM_UNLOCK

请注意,共享内存不会随着程序结束而自己主动消除,要么调用shmctl删除,要么自己用手敲命令去删除,否则永远留在系统中。


一个实际样例:

server端:

/*
    Write data to a shared memory segment
*/

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

#define BUFSZ 4096

int main()
{
    int shmid;
    char* shmbuf;
    key_t key;
    char* msg;
    int len;

    key=ftok("/tmp",0);

    if((shmid=shmget(key,BUFSZ,IPC_CREAT|0666))<0)
    {
    perror("shmget");
    exit(EXIT_FAILURE);
    }

    printf("segment created:%d
",shmid);
    system("ipcs -m");

    if((shmbuf=(char*)shmat(shmid,0,0))<0)
    {
    perror("shmat");
    exit(EXIT_FAILURE);
    }

    msg="This is the message written to the shared memory.";
    len=strlen(msg);
    strcpy(shmbuf,msg);

    printf("%s
Total %d characters have written to shared memory.
",msg,len);

    if(shmdt(shmbuf)<0)
    {
    perror("shmdt");
    exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);

}

client:

/*
    read data from a shared memory segment
 */
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ctype.h>
#include <unistd.h>

#define BUFSZ 4096

int main(int argc, char *argv[])
{
    int shmid;			
    char *shmbuf;		
    key_t key;
    int len;
            
    key = ftok("/tmp", 0);
     
    if((shmid = shmget(key, 0, 0)) < 0) 
    {
        perror("shmget");
        exit(EXIT_FAILURE);
    }        
    
    
    if((shmbuf = (char *)shmat(shmid, 0, 0)) < 0) 
    {
	    perror("shmat");
	    exit(EXIT_FAILURE);
    }
    
    
    printf("Info read form shared memory is:
%s
", shmbuf);
    
    if(shmdt(shmbuf) < 0) 
    {
	    perror("shmdt");
	    exit(EXIT_FAILURE);
    }
    
    if(shmctl(shmid,IPC_RMID,NULL) < 0)
    {
    perror("shmctl");
    exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);
}



原文地址:https://www.cnblogs.com/hrhguanli/p/4081613.html