- 论坛徽章:
- 0
|
使用共享内存的步骤还是相当简单的:
1、获得唯一的key值,书上提到ftok不一定能得到唯一的键值;
2、使用shmget创建或着获得共享内存区;
3、使用shmat将共享内存区附加到进程中;
4、使用共享内存区,。。。
5、与共享内存区脱离,但是记住这时共享内存区依然存在,必须等到内核重启。
6、申请的共享内存区的大小是有限制的。
#include
#include
#include
#include
#include
#include
#include
typedef struct{
char name[4];
int age;
}people;
int main(int argc, char *argv[])
{
int shm_id,i;
key_t key;
char temp;
people *p_map;
char *path = "/home/program/mmapfile.cc";
/*
使用 ftok根据path和作为项目标识符的单个字符生成key值确保进程间使用相同的 key
使用相同key值的shmget只会在第一次时创建新结构,*/
key = ftok(path,0);
if(key == -1)
{
perror("ftok error \n");
return -1;
}
shm_id = shmget(key,4096,IPC_CREAT);
if(shm_id == -1)
{
perror("shmget error \n");
return -1;
}
p_map = (people*)shmat(shm_id,NULL,0);
temp = 'a';
for(i = 0; i
#include
#include
#include
#include
/*完成从共享内存区的读出*/
typedef struct{
char name[4];
int age;
}people;
int main (int argc, char** argv)
{
int shm_id, i;
key_t key;
people *p_map;
char *path = "/home/program/mmapfile.cc";
key = ftok(path,0);
if(key == -1)
{
perror("ftok error \n");
return -1;
}
shm_id = shmget(key,4096,IPC_CREAT);
if(shm_id == -1)
{
perror("shmget error");
return -1;
}
p_map = (people*)shmat(shm_id,NULL,0);
for(i=0; i<10; i++)
{
printf("name:%s\t",(*(p_map+i)).name);
printf("age:%d\n",(*(p_map+i)).age);
}
system("ipcs -m");
if(shmdt(p_map) == -1)
{
perror("shmdt error\n");
return -1;
}
system("ipcs -m");
exit(EXIT_SUCCESS);
}
/
运行结果:
name:b age:20
name:c age:21
name:d age:22
name:e age:23
name:f age:24
name:g age:25
name:h age:26
name:i age:27
name:j age:28
name:k age:29
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00000001 32768 root 600 655360 2
0x00020069 262145 root 0 4096 1
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00000001 32768 root 600 655360 2
0x00020069 262145 root 0 4096 0
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/80698/showart_1225372.html |
|