shmget:不允许操作

时间:2017-08-28 01:47:06

标签: c linux

HugeTLB - Large Page Support in the Linux Kernel

stat_darwin.go     stat_linux.go   stat_openbsd.go  stat_unix.go
stat_dragonfly.go  stat_nacl.go    stat_plan9.go    stat_windows.go
stat_freebsd.go    stat_netbsd.go  stat_solaris.go

问题>我没有root权限来运行此代码。我该怎么做才能解决权限问题?

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

不使用SHM_HUGETLB,代码运行良好而没有问题。

$ gcc hugetlb-array.c -o hugetlb-array -Wall
$ ./hugetlb-array
shmget: Operation not permitted

1 个答案:

答案 0 :(得分:2)

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

具体来说,运行:

root@yourmachine$ setcap cap_ipc_lock=ep your_executable

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

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

另见Using setcap in linux

相关问题