linux进程通信之共享内存

来源:互联网 发布:手机阻拦广告软件 编辑:程序博客网 时间:2024/05/17 06:06

共享内存允许两个或多个进程共享一给定的存储区,因为数据不需要来回复制,所以是最快的一种进程间通信机制。共享内存可以通过mmap()映射普通文件(特殊情况下还可以采用匿名映射)机制实现,也可以通过系统V共享内存机制实现。应用接口和原理很简单,内部机制复杂。为了实现更安全通信,往往还与信号量等同步机制共同使用。下面主要介绍系统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删除,要么自己用手敲命令去删除,否则永远留在系统中。


一个实际例子:

服务器端:

/*    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 4096int 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\n",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\nTotal %d characters have written to shared memory.\n",msg,len);    if(shmdt(shmbuf)<0)    {    perror("shmdt");    exit(EXIT_FAILURE);    }    exit(EXIT_SUCCESS);}

客户端:

/*    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 4096int 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:\n%s\n", 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);}



0 0
原创粉丝点击