首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >shmget:不允许操作

shmget:不允许操作
EN

Stack Overflow用户
提问于 2017-08-28 09:47:06
回答 1查看 1.8K关注 0票数 3

HugeTLB - Large Page Support in the Linux Kernel

代码语言:javascript
复制
#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>我没有运行此代码的根权限。我应该怎么做来解决权限问题?

代码语言:javascript
复制
$ gcc hugetlb-array.c -o hugetlb-array -Wall
$ ./hugetlb-array
shmget: Operation not permitted

在不使用SHM_HUGETLB的情况下,代码运行得很好,没有问题。

代码语言:javascript
复制
$ ipcs -m

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x00000002 32768      myid         600        2097152    1
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-28 10:01:39

您需要CAP_IPC_LOCK功能。您可以使用setcap(8)将其添加到可执行文件中。

具体地说,运行:

代码语言:javascript
复制
root@yourmachine$ setcap cap_ipc_lock=ep your_executable

每次修改(重新编译/重新安装)你的可执行文件时,都必须重做这一步-否则会有一个巨大的安全漏洞。

如果你只需要在启动时这样做,你也应该考虑尽快删除权限,但这并不是必须的(如果有人真的关心,你可能会得到一个补丁)。

另请参阅Using setcap in linux

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45910849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档