linux 共享内存

来源:互联网 发布:js实现隐藏div 编辑:程序博客网 时间:2024/06/07 13:03
/*
   共享内存的写程序
1.首先调用ftok()函数将一个路径名转化为key
2.调用shmget();函数,来返回一个共享内存地址
3.调用shmat()函数映射共享内存到本进程内存空间
4.调用shmdt()函数删除共享内存.
*/
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#define SIZE 4096

typedef struct
{
    char name[4];
    int age;
}people;

int main(int argc,char **argv)
{
    int shm_id,i,fd;
     key_t key;
    char temp;
     people *p_map;
    char *name="/home/program/shm/shm.txt";
    if((fd=open("/home/program/shm/shm.txt",O_RDWR|O_CREAT))<0)//保证文件的存在,否则ftok()会出错
     {
         perror("open");
         exit(1);
     }
     key=ftok(name,0);
    if(key==-1)
     {
         perror("ftok error");
         exit(1);
     }
     shm_id=shmget(key,SIZE,IPC_CREAT);
    if(shm_id==-1)
     {
         perror("shmget");
         exit(1);
     }
     p_map=(people *)shmat(shm_id,NULL,0);
     temp='a';
    for(i=0;i<10;i++)
     {
         memcpy((*(p_map+i)).name,&temp,1);
         (*(p_map+i)).age=20+i;
         temp+=1;
     }
    if(shmdt(p_map)==-1)
         perror("detach error");
    return 0;
}
/*程序 read_shm.c*/
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#define SIZE 4096
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 *name="/home/program/shm/shm.txt";
     key=ftok(name,0);
    if(key==-1)
         perror("ftok error");
     shm_id=shmget(key,SIZE,IPC_CREAT);
     p_map=(people *)shmat(shm_id,NULL,0);
    for(i=0;i<10;i++)
     {
         printf("name:%s \n",(*(p_map+i)).name);
         printf("age %d \n",(*(p_map+i)).age);
     }
    if(shmdt(p_map)==-1)
         perror("detach error");
    return 0;
}
原创粉丝点击