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

标签 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 ");

}

最佳答案

( Answered in the comments - converted to a community Wiki Answer )

OP 写道:

The shmget needs to have the right permission (listed in bits/shm.h).

关于c++ - 为什么进程间共享内存需要sudo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28863310/

相关文章:

c++ - 从 C++ 设置变量时 QML 内存泄漏

jquery - 如何在 HTML/jquery 中为 Linux 终端生成 256 色调色板

json - 在使用 jq 验证 JSON 内容时结合多个测试

c++ - 尝试写入 Log4cpp 流时调试断言失败

c++ - 流迭代器 - 字节流

c++ - VS 2017 找不到 DirectX 包含文件

c++ - Rcpp 将 vector 复制到 vector

c++ - GCC 编译器错误 : unrecognized option '--export-dynamic'

linux - Elasticsearch 服务在几个小时后停止

c - Linux 中的网络性能调优