核心處理函數: void *shmat( int shmid , char *shmaddr , int shmflag );shmat()是用來允許本進程訪問一塊共享內存的函數。
int shmid是那塊共享內存的ID。
char *shmaddr是共享內存的起始地址
int shmflag是本進程對該內存的操作模式。如果是SHM_RDONLY的話,就是只讀模式。其它的是讀寫模式
成功時,這個函數返回共享內存的起始地址。失敗時返回-1
最近用到內存共享,收集整理了些資料,做了個簡單的對比
|
mmap系統調用 |
系統V共享內存 |
獲取共享
內存ID |
#include <sys/mman.h>
fd=open(name ,flag,mode);
if(fd<0)
…. |
#include <sys/ipc.h>
#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg); |
映射內存 |
ptr=mmap(NULL,len, PROT_READ|PROT_WRITE,
MAP_SHARED , fd , 0); |
void *shmat( int shmid , char *shmaddr , int shmflag ); |
解除映射 |
int munmap( void * addr, size_t len ) ; |
int shmdt( char *shmaddr );
使進程中的映射內存無效化,不可以使用。但是保留空間 |
其它 |
同步:
int msync ( void * addr , size_t len, int flags); |
控制:
shmctl( shmid , IPC_STAT , &buf );
// 取得共享內存的狀態
shmctl( shmid , IPC_RMID , &buf );
// 刪除共享內存–刪除共享內存,徹底不可用,釋放空間 |
posted on 2011-01-21 17:31
李陽 閱讀(3546)
評論(0) 編輯 收藏 引用 所屬分類:
Linux