Shared memory 補充說明

Download Report

Transcript Shared memory 補充說明

Shared memory 補充說明
Segmentation fault



許多人在工作站測試時,遇到segmentation
fault的問題,原因為shmget()沒有成功建立
空間
無法建立的原因大部分是因為工作站沒有
足夠的空間來建立shared memory
而空間不夠的原因為

系統給予程式一塊空間,不過程式沒有歸還系
統,因此這塊空間就一直被佔據著。隨著程式
越來越多,工作站的空間就不夠用了
空間不夠的解決辦法

目前只能先麻煩同學換別的工作站(bsd1~6
or linux1~6)測試看看
Shared Memory


請務必在程式最後加上以下兩項:
int shmdt(const void* shmaddr)


Detach a shred memory, shmaddr is the value
return by shmat()
int shmctl(int shmid, int IPC_RMID, NULL)

Remove a shared memory
如何刪除之前程式建立的SHM?


% ipcs –m

查看正在使用的shared memory空間

記下OWNER是屬於你的ID號碼
% ipcrm –m 327680

刪除此shared memory
shared memory範例更新
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int main()
{
int ShmID, *ShmPTR, status;
pid_t pid;
errno);
ShmID = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT|0666);
if (ShmID < 0) {
printf ("The shmget call failed, error number = %d\n",
}
exit(1);
ShmPTR = (int *) shmat(ShmID, NULL, 0);
if ((int) ShmPTR == -1) {
printf("The shmat call failed\n");
exit(1);
}
shared memory範例更新(續)
printf("Server has attached the shared memory\n");
pid = fork();
if (pid == -1) printf("failure!\n");
else if (pid == 0)
for(;;) {
if(ShmPTR[0] != 0) {
printf("child get number =
%d\n",ShmPTR[0]);
exit(1);
}
}
else {
srand(pid);
ShmPTR[0] = rand()%10+1;
printf("parent rand number = %d\n",ShmPTR[0]);
}
}
shmdt((void *) ShmPTR);
shmctl(ShmID, IPC_RMID, NULL);
exit(0);
Important!!!