key shmid owner perms bytes nattch status
0x00000000 5 luois1 600 16777216 2 dest
0x00000333 10 luois1 600 524288 2
共享内存的key;
共享内存的编号shmid;
创建的用户owner;
权限perms;
创建的大小bytes;
连接到共享内存的进程数nattach;
dest 为标记删除 此时的key为零,不能再使用,等到所有的进程断开链接的时候 清除
开启大页的命令行 echo 20 > /proc/sys/vm/nr_hugepages 用root权限 cat /proc/meminfo |grep Huge 查看大页
AnonHugePages: 0 kB
ShmemHugePages: 0 kB
HugePages_Total: 20
HugePages_Free: 20
HugePages_Rsvd: 0
HugePages_Surp: 0
Hugepagesize: 2048 kB
Hugetlb: 40960 kB
mmap 开启大页文件系统 mount none /文件路径 -t hugetlbfs
shmget()共享内存,只需要开启大页就可以了,不需要开启文件系统即可
#include <stdio.h>
#include<unistd.h>
#include<sys/sem.h>
#include<sys/shm.h>
#include<fcntl.h>
#include<string.h>
#include<strings.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#define N 10000000
#define SHM_HUGE_2M 1<<21
int main()
{
int semArrid = semget ( 1000 , 1, IPC_CREAT|0666);
if ( semArrid == -1 )
{
printf("semget is wrong \n");
}
int shmid;
shmid =shmget(1000,1<<20,IPC_CREAT|0666|SHM_HUGETLB|SHM_HUGE_2M);
if ( shmid==-1 )
{
printf("shmget is wrong \n");
}
int *p ;
p = (int*)shmat(shmid,NULL,0);
if ( p== NULL )
{
printf("shmat is wrong\n");
}
int ret = semctl(semArrid , 0,SETVAL,1);
if ( ret ==-1 )
{
printf("semctl is wrong \n");
}
struct sembuf sopp , sopv ;
sopp.sem_num= 0 ;
sopp.sem_op = -1;
sopp.sem_flg= SEM_UNDO;
sopv.sem_num = 0 ;
sopv.sem_op = 1;
sopv.sem_flg= SEM_UNDO;
if ( !fork() )
{
int i ;
for ( i = 0 ; i<N ; i++)
{
semop(semArrid,&sopp,1);
p[0]=p[0]+1;
semop(semArrid,&sopv,1);
}
}else{
int i ;
for ( i = 0 ; i<N ; i++)
{
semop(semArrid,&sopp,1);
p[0]=p[0]+1;
semop(semArrid,&sopv,1);
}
wait(NULL);
}
}
mmap 共享内存的使用,在有亲缘的进程中间使用,没有id 号码
#include <stdio.h>
#include<sys/mman.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(int argc , char **argv)
{
if ( argc < 2 )
{
perror("argc");
}
int fd= open(argv[1],O_RDWR);
if ( fd ==-1 )
{
perror("open");
}
char *p = (char *)mmap(NULL, 20 , PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if ( p ==NULL )
{
perror("mmap");
}
if ( fork() ==0)
{
strcpy(p , "world hello\n");
}else{
sleep(1);
printf("p = %s\n",p);
wait(NULL);
}
return 0;
}
mmap大页的使用
必须要挂载,必须使用挂载的目录,权限的问题要考虑
#include <stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<sys/mman.h>
#include<sys/fcntl.h>
#define Hugepage 1<<21
int main(int argc ,char ** argv)
{
if(argc <2)
{
perror("argc");
}
int fd = open(argv[1],O_RDWR);
if ( fd ==-1 )
{
perror("open");
}
char * p = (char *) mmap(NULL,Hugepage,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if (fork()==0)
{
strcpy(p,"helloworld");
}else{
sleep(10);
printf("p= %s\n",p);
wait(NULL);
}
munmap(p,Hugepage);
}