在Ubuntu14.04上如何创建共享内存

 时间:2026-02-12 08:08:55

1、共享内存的使用步骤:

 1)创建:key_t key=ftok(PATH,proj); int shmid=shmget(key,SIZE,IPC_CREAT | 0600);

 2)映射:paddr=shmat(shmid,NILL,0);

 3)操作:利用内存操作函数;

 4)断开:shmdt(paddr);

 5)回收:shmctl(shmid,IPC_RMID,NULL);

在Ubuntu14.04上如何创建共享内存

2、用于写的代码:

#include <stdio.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <stdlib.h>

#include <string.h>

#define KEY_PATH "/home/xxx"

int main()

{

key_t key;

key=ftok(KEY_PATH,1);

printf("key:%#x\n",key);

if(key < 0)

{

perror("ftok");

exit(-1);

}

int shmid;

if(-1 == (shmid=shmget(key,64,IPC_CREAT | 0600)))//创建

{

perror("shmget");

exit(EXIT_FAILURE);

}

// puts("创建共享内存成功!");

printf("key:%d\n",shmid);

char *padrr=(char *)shmat(shmid,NULL,0);//映射,要进行类型转换

if(padrr == NULL)

{

perror("shmat");

exit(EXIT_FAILURE);

}

strcpy(padrr,"hello");

shmdt(padrr);//断开

    return 0;

}

在Ubuntu14.04上如何创建共享内存

在Ubuntu14.04上如何创建共享内存

3、用于读的代码:

#include <stdio.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/shm.h>

#include <stdlib.h>

#include <string.h>

#define KEY_PATH "/home/xxx"

int main()

{

key_t key;

key=ftok(KEY_PATH,1);

printf("key:%#x\n",key);

if(key < 0)

{

perror("ftok");

exit(-1);

}

int shmid;

if(-1 == (shmid=shmget(key,64,IPC_CREAT | 0600)))//创建

{

perror("shmget");

exit(EXIT_FAILURE);

}

// puts("创建共享内存成功!");

printf("key:%d\n",shmid);

char *padrr=(char *)shmat(shmid,NULL,0);//映射,此处一定进行类型转换

if(padrr == NULL)

{

perror("shmat");

exit(EXIT_FAILURE);

}

puts(padrr);

shmdt(padrr);//断开

shmctl(shmid,IPC_RMID,NULL);//回收

    return 0;

}

在Ubuntu14.04上如何创建共享内存

在Ubuntu14.04上如何创建共享内存

4、使用下面的命令编译:

“gcc shm_r.c -o read”

“gcc shm_w.c -o write”

先运行写内存程序:

命令:“./write”:

在Ubuntu14.04上如何创建共享内存

5、这里运行读内存程序:

命令:“./read”:

在Ubuntu14.04上如何创建共享内存

  • 怎样鉴别玉器真假?
  • 我最喜欢爸爸的怎么填
  • 永远好朋友的数字怎么表示
  • 鲫鱼蒸蛋的做法
  • 大多数实木地热地板为什么都是带锁扣技术的?
  • 热门搜索
    人力资源的特点 凉拌海带 承德避暑山庄旅游攻略 凉拌西兰花的做法 溶血性黄疸怎么治疗 现在最佳旅游地 早孕了怎么办 吉林师范大学怎么样 lol怎么亮徽章 宝宝老是吐奶怎么办