【问题标题】:shmget: Operation not permittedshmget:不允许操作
【发布时间】:2017-08-28 01:47:06
【问题描述】:

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;
}

问题> 我没有运行此代码的 root 权限。如何解决权限问题?

$ 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

【问题讨论】:

    标签: c linux


    【解决方案1】:

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

    具体来说,运行:

    root@yourmachine$ setcap cap_ipc_lock=ep your_executable
    

    每次修改(重新编译/重新安装)可执行文件时都必须重做 - 否则会出现巨大的安全漏洞。

    如果您只需要在启动时执行此操作,您还应该考虑尽快放弃权限,但这不是必需的(如果有人真的关心,您可能会得到一个补丁)。

    另见Using setcap in linux

    【讨论】:

    • 您可以在这里提供更多详细信息吗?我阅读了链接,但仍然不知道这个问题。
    • 你的意思是我必须先获得root权限才能运行我的代码?不幸的是,我无法获得root权限。
    • 是的,您仍然需要一次 root 权限(但不是每次运行都需要)。嗯,除非你输入一个新的 IPC 命名空间(这需要输入一个新的 UID 命名空间)?请参阅unshare(1) - 我还没有尝试过这种事情,只是作为无权限的 chroot/mount 替代品。
    猜你喜欢
    • 1970-01-01
    • 2012-01-03
    • 2021-02-10
    • 2021-01-01
    • 2014-11-01
    • 2014-06-30
    • 2012-03-19
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多