服务器端:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 26
int main(int argc,char* argv[])
{
key_t key = ftok("/home/kingoal/",2);
int shmid = shmget(key,SHM_SIZE,IPC_CREAT|0600);
if(shmid == -1)
{
perror("shmget");
exit(-1);
}
char* pMem = (char*)shmat(shmid,NULL,0);
if(pMem == (char*) -1)
{
perror("shmat");
exit(-1);
}
printf("Shared Memory: %p\n", pMem);
for(int i = 0;i<SHM_SIZE;i++)
{
pMem[i]='a'+i;
}
while(pMem[0]!='*')
sleep(1);
int retcode = shmdt(pMem);
if(retcode == -1)
{
perror("shmdt");
exit(-1);
}
retcode = shmctl(shmid,IPC_RMID,NULL);
if(retcode == -1)
{
perror("shmctl");
exit(-1);
}
return 0;
}
客户端:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 26
int main(int argc,char* argv[])
{
key_t key = ftok("/home/kingoal/",2);
int shmid = shmget(key,SHM_SIZE,0600);
if(shmid == -1)
{
perror("shmget");
exit(-1);
}
char* pMem = (char* )shmat(shmid,NULL,0);
if(pMem == (char*) -1)
{
perror("shmat");
exit(-1);
}
printf("Client: Shared Memory at %p\n", pMem);
for(int i=0;i<SHM_SIZE;i++)
{
putchar(pMem[i]);
}
putchar('\n');
pMem[0]='*';
shmdt(pMem);
return 0;
}
执行结果:
首先是服务器端的执行结果
[kingoal@sunrise ~/dev/cxx]$ ./shmserv
Shared Memory: 0x28294000
[kingoal@sunrise ~/dev/cxx]$
下面是客户端的执行结果
[kingoal@sunrise ~/dev/cxx]$ ipcs
Message Queues:
T ID KEY MODE OWNER GROUP
Shared Memory:
T ID KEY MODE OWNER GROUP
m 327680 39531450 --rw------- kingoal kingoal
Semaphores:
T ID KEY MODE OWNER GROUP
[kingoal@sunrise ~/dev/cxx]$ shmclient
Client: Shared Memory at 0x28294000
abcdefghijklmnopqrstuvwxyz
[kingoal@sunrise ~/dev/cxx]$ ipcs
Message Queues:
T ID KEY MODE OWNER GROUP
Shared Memory:
T ID KEY MODE OWNER GROUP
Semaphores:
T ID KEY MODE OWNER GROUP
[kingoal@sunrise ~/dev/cxx]$