寫在前面:小生純業餘選手,開此博僅僅是爲了積累,純當筆記來用。如有看官光臨小生博客,請不要相信我的代碼就是正確的。如果您發現了錯誤也懇請耽誤您一點時間,請您在下面指出來,不勝感激!
如果發現一些筆記的說法完全是錯誤的請建議我刪除!
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;
}