三、
posix
共享記憶體函式
posix
共享記憶體區涉及兩個步驟:
1、指定乙個名字引數呼叫
shm_open,
以建立乙個新的共享記憶體區物件或開啟乙個以存在的共享記憶體區物件。
2、呼叫
mmap
把這個共享記憶體區對映到呼叫程序的位址空間。傳遞給
shm_open
的名字引數隨後由希望共享該記憶體區的任何其他程序使用。5.
名稱::shm_open功能:
開啟或建立乙個共享記憶體區
標頭檔案:
#include
函式原形
:int shm_open(const char *name,int oflag,mode_t mode);引數:
name
共享記憶體區的名字
cflag
標誌位mode
許可權位返回值:
成功返回
0,出錯返回-1
oflag
引數必須含有
o_rdonly
和o_rdwr
標誌,還可以指定如下標誌:
o_creat,o_excl
或o_trunc.
mode
引數指定許可權位,它指定
o_creat
標誌的前提下使用。
shm_open
的返回值是乙個整數描述字,它隨後用作
mmap
的第五個引數。6.
名稱::shm_unlink功能:
刪除乙個共享記憶體區
標頭檔案:
#include
函式原形
:int shm_unlink(const char *name);引數:
name
共享記憶體區的名字
返回值:
成功返回
0,出錯返回-1
shm_unlink
函式刪除乙個共享記憶體區物件的名字,刪除乙個名字僅僅防止後續的
open,mq_open
或sem_open
呼叫取得成功。
下面是建立乙個共享記憶體區的例子:
/*shm_open.c
建立共享記憶體區
*/ #include
#include
#include
int main(int argc,char **argv)
shm_id=shm_open(argv[1],o_rdwr|o_creat,0644);
printf(「shmid:%d/n」,shm_id);
shm_unlink(argv[1]);
}下面是執行結果,注意編譯程式我們要加上「
-lrt
」引數。
#cc –lrt –o shm_open shm_open.c
#./shm_open test
shm_id:3
四、
ftruncate
和
fstat
函式
普通檔案或共享記憶體區物件的大小都可以通過呼叫
ftruncate
修改。7.名稱
::ftruncate功能:
調整檔案或共享記憶體區大小
標頭檔案:
#include
函式原形
:int ftruncate(int fd,off_t length);引數:
fd
描述符length
大小返回值:
成功返回
0,出錯返回-1
當開啟乙個已存在的共享記憶體區物件時,我們可呼叫
fstat
來獲取有關該物件的資訊。8.
名稱::fstat功能:
獲得檔案或共享記憶體區的資訊
標頭檔案:
#include
#include
#include
函式原形
:int stat(const char *file_name,struct stat *buf);引數:
file_name
檔名buf stat
結構返回值:
成功返回
0,出錯返回-1
對於普通檔案
stat
結構可以獲得
12個以上的成員資訊,然而當
fd指代乙個共享記憶體區物件時,只有四個成員含有資訊。
struct stat;
/*shm_show.c
顯示共享區資訊
*/ #include
#include
#include
#include
#include
#include
int main(int argc,char **argv)
shm_id=shm_open(argv[1],o_rdwr|o_creat,0644);/*
建立共享記憶體
*/ ftruncate(shm_id,100);/*
修改共享記憶體的開啟
*/ fstat(shm_id,&buf); /*
把共享記憶體的資訊記錄到
buf中
*/ printf(「uid_t:%d/n」,buf.st_uid); /*
共享記憶體區所有者
id*/
printf(「git_t:%d/n」,buf.st_gid); /*
共享記憶體區所有者組
id*/
printf(「size :%d/n」,buf.st_size); /*
共享記憶體區大小
*/ }
下面是執行結果:
#cc –lrt –o shm_show shm_show.c
#./shm_show test
uid_t:0
git_t:0
size:100
Posix多執行緒程式設計學習筆記(六) 共享記憶體(3)
五 共享記憶體區的寫入和讀出 上面我們介紹了 mmap 函式,下面我們就可以通過這些函式,把程序對映到共享記憶體區。然後我們就可以通過共享記憶體區進行程序間通訊了。下面是共享記憶體區寫入的例子 shm write.h寫入 讀出共享記憶體區 include include include includ...
Posix多執行緒程式設計學習筆記(六) 共享記憶體(2)
三 posix共享記憶體函式 posix共享記憶體區涉及兩個步驟 1 指定乙個名字引數呼叫shm open,以建立乙個新的共享記憶體區物件或開啟乙個以存在的共享記憶體區物件。2 呼叫mmap把這個共享記憶體區對映到呼叫程序的位址空間。傳遞給shm open的名字引數隨後由希望共享該記憶體區的任何其他...
Posix多執行緒程式設計學習筆記(六) 共享記憶體(3)
五 共享記憶體區的寫入和讀出 上面我們介紹了 mmap 函式,下面我們就可以通過這些函式,把程序對映到共享記憶體區。然後我們就可以通過共享記憶體區進行程序間通訊了。下面是共享記憶體區寫入的例子 shm write.h寫入 讀出共享記憶體區 include include include includ...