我正在使用共享内存在 linux 上不相关的进程之间进行通信。我只希望我在 struct ipc_perm 中指定的进程能够访问共享内存。但似乎代码无效:
进程A:创建共享内存
int main (int argc, char* argv[]){
int segment_id;
key_t key;
key = 56789;
char* shared_memory;
int shm_size = 512;
segment_id = shmget(key, shm_size, IPC_CREAT | 0666);
if (segment_id < 0){
perror("shmget");
exit(1);
}else {
struct shmid_ds shmbuf;
struct ipc_perm perms;
//here i specified the process whose
//uid is 1234 has the read/write access
//to this shared memory
perms.uid = 1234;
perms.gid = 2000;
perms.mode = 0660;
shmctl(segment_id, IPC_STAT, &shmbuf);
shmbuf.shm_perm = perms;
int ret = shmctl(segment_id, IPC_SET, &shmbuf);
if (ret < 0){
perror("shmctl IPC_SET");
exit(1);
}
}
shared_memory = (char*)shmat(segment_id, NULL, 0);
if (shared_memory == (char*) -1){
perror("shmat");
exit(1);
}
sprintf(shared_memory, "Server Updated The Memory -PID- %lu", getpid());
while(*shared_memory != '*')
sleep(1);
printf("The memory has been updated: \n %s\n", shared_memory);
sleep(5);
shmdt(shared_memory);
shmctl(segment_id, IPC_RMID, 0);
return 0;
}
进程B:访问进程A创建的共享内存
int main(){
int segment_id;
key_t key;
key = 56789;
char* shared_memory, *s;
int shm_size = 512;
segment_id = shmget(key, shm_size, 0666);
if (segment_id < 0){
perror("shmget");
exit(1);
}
shared_memory = (char*)shmat(segment_id, NULL, 0);
if (shared_memory == (char*) -1){
perror("shmat");
exit(1);
}
for (s = shared_memory; *s != NULL; s++)
putchar(*s);
putchar('\n');
sprintf(shared_memory, "*Client Updated The Memory - pid-%lu", getpid());
return 0;
}
在我的测试过程中,进程 B 始终具有对进程 A 创建的共享内存的读/写访问权限。为什么会发生这种情况?(我在ubuntu上运行,打开两个控制台分别启动上述进程。)