共享内存是用内存的一部分,每一个进程都有一个指向此内存端的指针,依靠访问权限的设置,所有进程都可以读取这一块空间中的数据。因此进程间的资源是共享的,而不是被复制来复制去。共享内存端对于进程而言,类似于共享变量对于线程一样。
一、共享内存段的一些基本概念
1. 共享内存段在内存中不依赖于进程的存在而存在
2. 共享内存段有自己的名字,称为关键字(key)。
3. 关键字是一个整形数
4.共享内存段有自己的拥有者以及权限位。
5.进程可以连接到某共享内存段,并且获得指向此段的指针。
二、使用共享内存段
(1)如何得到共享内存(shmget)
int seg_id = shmget(key,size-of-segment,flags);
如果内存段存在,函数shmget找到它的位置,如果不存在,可以通过在flags值中指定一个创建此段和初始化权限模式的请求
(2)如何将进程连接到某个共享内存端(shmat)
void ptr = *shmat(seg_id,null,flags);
(3)如何与共享内存进行读写交互
strcpy(ptr,"hello");
memcpy()、ptr[i]及其他一些通用的指针操作。
(4)使用完共享内存要注销
shmctl( seg_id, IPC_RMID, NULL );
三、使用共享内存段的例程:
service:
#include <stdio.h>
#include <sys/shm.h>
#include <time.h>
#define TIME_MEM_KEY 99 /* like a filename */
#define SEG_SIZE ((size_t)100) /* size of segment */
#define oops(m,x) { perror(m); exit(x); }
main()
{
int seg_id;
char *mem_ptr, *ctime();
long now;
int n;
/* create a shared memory segment */
seg_id = shmget( TIME_MEM_KEY, SEG_SIZE, IPC_CREAT|0777 );
if ( seg_id == -1 )
oops("shmget", 1);
/* attach to it and get a pointer to where it attaches */
mem_ptr = shmat( seg_id, NULL, 0 );
if ( mem_ptr == ( void *) -1 )
oops("shmat", 2);
/* run for a minute */
for(n=0; n<60; n++ ){
time( &now ); /* get the time */
strcpy(mem_ptr, ctime(&now)); /* write to mem */
sleep(1); /* wait a sec */
}
/* now remove it */
shmctl( seg_id, IPC_RMID, NULL );
}
client:
#include <stdio.h>
#include <sys/shm.h>
#include <time.h>
#define TIME_MEM_KEY 99 /* kind of like a port number */
#define SEG_SIZE ((size_t)100) /* size of segment */
#define oops(m,x) { perror(m); exit(x); }
main()
{
int seg_id;
char *mem_ptr, *ctime();
long now;
/* create a shared memory segment */
seg_id = shmget( TIME_MEM_KEY, SEG_SIZE, 0777 );
if ( seg_id == -1 )
oops("shmget",1);
/* attach to it and get a pointer to where it attaches */
mem_ptr = shmat( seg_id, NULL, 0 );
if ( mem_ptr == ( void *) -1 )
oops("shmat",2);
printf("The time, direct from memory: ..%s", mem_ptr);
shmdt( mem_ptr ); /* detach, but not needed here */
}
四、避免竞态
首先,客户端必须有对共享内存段的访问读权限。共享内存段拥有一个权限系统,它的工作原理和文件权限系统类似。共享内存段有自己的拥有者并且为用户、组或者其他成员设置了权限位,来控制他们各自的访问权限。正因为有如此的特性,才可以让服务器只有写权限而客户只有读权限。而多个客户,也可以同时从共享内存段读数据。
但是,服务器通过调用一个运行在用户空间的库函数strcpy来更新共享的内存段。如果客户端正好在服务器写入共享内存的时候读取共享内存段,那么数据就出错了。
我们自然想到了锁对资源的控制,内核提供了一种进程间加锁的机制-------信号量。