gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:51 25 4
gpt4 key购买 nike

我正在通过共享内存程序学习进程间通信,并编写了一个非常简单的程序。它运行良好,只是需要 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com