共享内存的访问控制不起作用?

时间:2013-08-11 03:57:48

标签: c linux permissions ipc shared-memory

我使用共享内存在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上运行,打开两个控制台,分别启动上述过程。)

1 个答案:

答案 0 :(得分:0)

如果两个进程都有UID 1234或GID 2000,那么它们都应该可以访问共享内存段。您在源代码中的评论:“其uid为1234的进程”似乎表明您将术语UID(用户标识符)与PID(进程标识符)混淆。

据我所知,无法通过PID将访问共享内存段限制为特定的一组进程。限制特定用户运行的流程 - 通过在调用shm_perm.uid时在shm_ctl(...IPC_SET...)中指定该用户的ID - 通常就足够了。如果要限制可以访问该段的进程,请限制您运行的访问该段的进程。