2017-08-28 146 views
2

HugeTLB - Large Page Support in the Linux Kernelshmget的:操作不允許

#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 

回答

2

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

具體來說,運行:

[email protected]$ setcap cap_ipc_lock=ep your_executable 

這完全有你的可執行文件被修改(編譯/重新安裝)的時間要重做 - 否則將是一個巨大的安全漏洞。

如果您只需要在啓動時執行此操作,您還應該考慮儘快刪除權限,但這不是必需的(如果有人真的在意,您可能會獲得補丁)。

另請參見Using setcap in linux

+0

您可以在此處提供更多詳細信息嗎?我閱讀了這個鏈接,但仍然不知道這個問題。 – q0987

+0

你的意思是我必須先獲得root權限才能運行我的代碼?不幸的是,我無法獲得根權限。 – q0987

+0

是的,你仍然需要root權限(但不是每次運行)。嗯,除了可能如果你輸入一個新的IPC命名空間(這需要輸入一個新的UID命名空間)?參見'unshare(1)' - 我還沒有嘗試過這種方法,只是作爲一個無權限的chroot/mount替換。 – o11c