HugeTLB - Large Page Support in the Linux Kernel
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#define MB_1 (1024*1024)
#define MB_8 (8*MB_1)
char *a;
int shmid1;
void init_hugetlb_seg()
{
shmid1 = shmget(2, MB_8, SHM_HUGETLB
| IPC_CREAT | SHM_R
| SHM_W);
if ( shmid1 < 0 ) {
perror("shmget");
exit(1);
}
printf("HugeTLB shmid: 0x%x\n", shmid1);
a = shmat(shmid1, 0, 0);
if (a == (char *)-1) {
perror("Shared memory attach failure");
shmctl(shmid1, IPC_RMID, NULL);
exit(2);
}
}
void wr_to_array()
{
int i;
for( i=0 ; i<MB_8 ; i++) {
a[i] = 'A';
}
}
void rd_from_array()
{
int i, count = 0;
for( i=0 ; i<MB_8 ; i++)
if (a[i] == 'A') count++;
if (count==i)
printf("HugeTLB read success :-)\n");
else
printf("HugeTLB read failed :-(\n");
}
int main(int argc, char *argv[])
{
init_hugetlb_seg();
printf("HugeTLB memory segment initialized !\n");
printf("Press any key to write to memory area\n");
getchar();
wr_to_array();
printf("Press any key to rd from memory area\n");
getchar();
rd_from_array();
shmctl(shmid1, IPC_RMID, NULL);
return 0;
}Question>我没有运行此代码的根权限。我应该怎么做来解决权限问题?
$ gcc hugetlb-array.c -o hugetlb-array -Wall
$ ./hugetlb-array
shmget: Operation not permitted在不使用SHM_HUGETLB的情况下,代码运行得很好,没有问题。
$ ipcs -m
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00000002 32768 myid 600 2097152 1发布于 2017-08-28 10:01:39
您需要CAP_IPC_LOCK功能。您可以使用setcap(8)将其添加到可执行文件中。
具体地说,运行:
root@yourmachine$ setcap cap_ipc_lock=ep your_executable每次修改(重新编译/重新安装)你的可执行文件时,都必须重做这一步-否则会有一个巨大的安全漏洞。
如果你只需要在启动时这样做,你也应该考虑尽快删除权限,但这并不是必须的(如果有人真的关心,你可能会得到一个补丁)。
https://stackoverflow.com/questions/45910849
复制相似问题