-- create a shared memory
#: cat create.C
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
using namespace std;
int main()
{
int shmid;
key_t key=0x1234;
//if((shmid=shmget(key,32,0666|IPC_CREAT|IPC_EXCL)) < 0)
if((shmid=shmget(key,32,0666|IPC_CREAT)) < 0)
{
printf("shmid failed. Exit/n");
exit(1);
}
else
printf("shmid succes id=%d/n",shmid);
}
-- Write into shared memory --
#: cat write.C
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "Amsg.h"
using namespace std;
int main()
{
int shmid=SHMID;
char *shmaddress;
shmaddress=(char *)shmat(shmid,NULL,0);
if((int)shmaddress == -1)
{
printf("shmat failed. Exit/n");
exit(3);
}
else
{
printf("shmat success return 0x%x/n",shmaddress);
}
Amsg * msg = new (shmaddress) Amsg();
if (msg != NULL)
{
printf("new Amsg object was created at 0x%x/n",msg);
msg->setName(1,(char*)"I am boy!/n");
}
if((shmdt(shmaddress)) < 0)
printf("shmdt failed. Exit/n");
}
-- Check shared memory --
#: cat info.C
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
int main()
{
int shmid=SHMID;
struct shmid_ds dsbuf;
if((shmctl(shmid,IPC_STAT,&dsbuf))<0)
{
printf("shmctl failed. Exit/n");
exit(4);
}
printf("shmctl, shared memory creater: %d/n",dsbuf.shm_cpid);
printf("shmctl, shared memory size: %d/n",dsbuf.shm_segsz);
printf("shmctl, shared memory last access: %d/n",dsbuf.shm_lpid);
}
#
# 'ipcs -am' can list out all shared memory
#
-- Read out from shared memory --
#: write.C
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "Amsg.h"
using namespace std;
int main()
{
int shmid=SHMID;
char *shmaddress;
struct shmid_ds dsbuf;
if((shmaddress=(char *)shmat(shmid,0,0))<0)
{
printf("shmat faild. Exit/n");
exit(5);
}
Amsg * msg = reinterpret_cast<Amsg *>(shmaddress);
char * output = msg->getName(1);
printf("Read out from shared memory: %s/n",output);
if((shmdt(shmaddress)) < 0)
printf("shmdt failed. Exit/n");
}
-- Delete shared memory --
#: cat delete.C
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
int main()
{
int shmid=SHMID;
if(shmctl(shmid,IPC_RMID,NULL) < 0)
{
printf("shmctl failed. Exit/n");
exit(7);
}
}
#
# 'ipcrm -m $id' can remove shared memory identified by $id.
#
-- appendix --
#: Amsg.h
class Amsg
{
public:
Amsg() {}
public:
void setName(int i, char *name)
{
this->id = i;
strncpy(this->value,name,20);
}
char * getName(int i)
{
if (i==this->id)
return this->value;
else
return (char *)"NULL";
}
public:
int id;
char value[20];
};
-- appendix --
#: cat Makefile
CC = .../bin/CC
all: create info write read delete
create : create.o
CC -o $@ $^
SHMID = $(shell ./create | awk -F/= '{print $$2}')
info: info.o
CC -o $@ -DSHMID=$(SHMID) $^
write: write.o
CC -o $@ -DSHMID=$(SHMID) $^
read: read.o
CC -o $@ -DSHMID=$(SHMID) $^
delete: delete.o
CC -o $@ -DSHMID=$(SHMID) $^
%.o: %.C
CC -c -o $@ -DSHMID=$(SHMID) $^
.PHONY:clean
clean:
rm -rf *.o a.out create info write read delete