为什么进程间共享内存需要sudo?

时间:2015-03-04 19:35:28

标签: c++ linux

我正在通过共享内存程序学习进程间通信,并编写了一个非常简单的程序。它运行良好,但它需要sudo才能正常运行。

如果我没有输入sudo,则会出现这样的错误

"shmat error: Permission denied " 

用于创建共享内存的进程,并且出现类似

的错误
"Segmentation fault (core dumped)" 

尝试从共享内存中读取的进程。有没有人知道导致这种或这种类型的程序确实需要root的原因?感谢。

/*
 *This is the process that creates the shared memory
 */
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

void main(int argc, char** argv)
{
    int shm_id,i;
    key_t key;
    unsigned long *shmap;
    char* name = "/home/veydan/code/cpshm"; // 0 size file
    key = ftok(name,1234);
    if ( key == -1 )
       perror("ftok error");
    shm_id = shmget(key,20480000,IPC_CREAT);
    if( shm_id == -1 ) {
       perror("shmget error");
       return;
    }
    shmap = (unsigned long*)shmat(shm_id,NULL,0);
    if(shmap==-1) {
       perror("shmat error");
       return;
    }
    for ( i = 0; i < 512; i++ )
       *(shmap+i) = i;

    if ( shmdt(shmap)==-1 )
       perror(" detach error ");
}

/*
 *This is the process that reads from the shared memory
 */
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

void main(int argc, char** argv)
{
   int shm_id,i;
   key_t key;
   unsigned long *shmap, tmp;
   char* name = "/home/veydan/code/cpshm";
   key = ftok(name,1234);
   if ( key == -1 )
      perror("ftok error");
   shm_id = shmget(key,20480000,IPC_CREAT);    
   if ( shm_id == -1 ) {
      perror("shmget error");
      return;
   }     
   shmap = (unsigned long*)shmat(shm_id,NULL,0);
   for ( i = 0; i < 512; i++ ) {
      tmp = *(shmap+i);
      printf("%lu ", tmp);
      *(shmap+i) = tmp*2;
   }    
   if( shmdt(shmap) == -1 )
      perror(" detach error ");

}

1 个答案:

答案 0 :(得分:0)

Answered in the comments - converted to a community Wiki Answer

OP写道:

  

shmget需要拥有正确的权限(在bits/shm.h中列出)。