共享内存

      共享内存机制是3个IPC机制的第二个,它允许两个不同的进程访问同一块逻辑内存,共享内存是在两个正在运行的进程之间传递数据的一种非常有效的方式:

    头文件:

      #include <sys/shm.h>

    主要函数:

      int shmget(key_t key, size_t size, int shmflg);

      //得到共享内存的标识号

      void *shmat(int shmid, const void *shmaddr, int shmflg);

      //获得内存标示号对应的共享地址

      void *shmat(int shmid, const void *shmaddr, int shmflg);

      //解除对应标识号的关联 

      int shmctl(int shmid, int cmd, struct shmid_ds *buf);

      //删除对应内存标识号的共享物理地址

      接下来是代码:申请一块共享的内存,往内存里面写数据:

      

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 #include <signal.h>
  5 #include <fcntl.h>
  6 #include <sys/ipc.h>
  7 #include <sys/msg.h>
  8 #include <sys/shm.h>
  9 
 10 
 11 int main()
 12 {
 13     //得到共享内存标识符
 14     int ret;
 15     ret=shmget(IPC_PRIVATE ,1,IPC_CREAT);
 16     if(ret < 0)
 17     {
 18         perror("shmget!
");
 19         exit(EXIT_FAILURE);
 20     }
 21     printf("ret is %d
",ret);
 22     //3342380
 23     //得到共享地址
 24     char *shm_addr =(char*)shmat(ret,NULL,0);
 25     printf("shm_addr is %p
",shm_addr);
 26     if(shm_addr ==(char*)-1)
 27     {
 28         perror("shm_addr error!
");
 29         exit(EXIT_FAILURE);
 30     }
 31 
 32     char *buf="hello shmaddr!
";
 33     //向共享地址写数据
 34     strcpy(shm_addr,buf);
 35 
 36     shmdt(shm_addr);
 37 }
 38 
 39 
 40 
 41 

    读: read

    

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 #include <signal.h>
  5 #include <fcntl.h>
  6 #include <sys/ipc.h>
  7 #include <sys/msg.h>
  8 #include <sys/shm.h>
  9 
 10 int main()
 11 {
 12 #if 0
 13     int ret;    
 14     ret=shmget(IPC_PRIVATE , 1,IPC_CREAT);
 15     if(ret < 0)
 16     {
 17         perror("shmget!
");
 18         exit(EXIT_FAILURE);
 19     }
 20     printf("ret is %d
",ret);
 21     //3342380
 22 #endif
 23     //得到共享内存的地址
 24     char *shm_addr =(char*)shmat(3375149,NULL,0);
 25     printf("shm_addr is %p
",shm_addr);
 26     if(shm_addr ==(char*)-1)
 27     {
 28         perror("shm_addr error!
");
 29         exit(EXIT_FAILURE);
 30     }
 31 
 32     //char *buf="hello shmaddr!
";
 33     //从共享内存 里读数据
 34     char buf[1024];
 35     strcpy(buf,shm_addr);
 36     printf("buf is %s
",buf);
 37 
 38     shmdt(shm_addr);
 39     //解除关联
 40     //
 41     if(shmctl(3375149,IPC_RMID,0)==-1)
 42     //删除共享内存地址
 43     {
 44         perror("shmctl!
");
 45         exit(EXIT_FAILURE);
 46     }
 47         exit(EXIT_SUCCESS);
 48 }
 49 
 50 
 51 
 52 
 53 
~                    

    

  运行结果:

    

  通过  ipcs -m可以查看相关的共享内存的情况:

      

            

    

      

      

原文地址:https://www.cnblogs.com/hongzhunzhun/p/4570100.html