Linux进程间通信-基于内存(共享内存)

来源:互联网 发布:android系统源码是什么 编辑:程序博客网 时间:2024/05/22 15:15

写在前面:小生纯业余选手,开此博仅仅是为了积累,纯当笔记来用。如有看官光临小生博客,请不要相信我的代码就是正确的。如果您发现了错误也恳请耽误您一点时间,请您在下面指出来,不胜感激!

如果发现一些笔记的说法完全是错误的请建议我删除!



Linux中查看共享内存的指令ipcs,ipcs -m,ipcs -q,ipcs -s,ipcrm -q shmid


使用内存共享机制实现进程间通信的过程:

使用shmget创建共享内存,得到一个ID  

使用shmat把ID映射成虚拟地址(attach)

使用虚拟地址访问内核共享内存(与访问普通内存一样)
使用 shmdt卸载虚拟地址
使用shctl删除共享内存 ,其中shctl的作用所有修改/获取共享内存的属性的功能

共享内存的属性包括(key,shmid,owner,perms,byte,nattch,dest)


以下代码展现基于共享内存的进程间通信机制

ftok产生一个key标示着一个共享内存,进程可以通过这个key获取这个共享内存。(这里的这种机制与RSA算法的精神有一点类似)

#include<sys/shm.h>#include<sys/ipc.h>#include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(){    key_t key;    int shmid;    int *p;    key = ftok(".",255);    if(key == -1)    {        printf("ftok error:%m\n");        exit(-1);    }        shmid = shmget(key,4,IPC_CREAT|IPC_EXCL|0666);    if(shmid == -1)    {        printf("get error:%m\n");        exit(-1);    }            p = static_cast<int*>(shmat(shmid,0,0));    if(p == (int*)-1)    {        printf("at error%m\n");        exit(-1);    }        while(1)    {        *p = 999;        sleep(1);    }    shmdt(p);    shmctl(shmid,IPC_RMID,0);    return 0;} 


#include<stdio.h>#include<string.h>#include<stdlib.h>#include<signal.h>#include<sys/shm.h>#include<sys/ipc.h>#include<unistd.h>int main(){    key_t key;    int shmid;    int *p;        key = ftok(".",255);    if(key == -1)    {        printf("ftok error:%m\n");        exit(-1);    }        shmid = shmget(key,4,0);    if(shmid == -1)    {        printf("get error:%m\n");        exit(-1);    }        p = static_cast<int*>(shmat(shmid,0,0));    if( p == reinterpret_cast<int*>(-1) )    {        printf("attach error:%m\n");        exit(-1);    }        while(1)    {        sleep(1);        printf("%d\n",*p);    }    return 0;    }




0 0
原创粉丝点击