自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

一文搞定Linux共享內(nèi)存原理

系統(tǒng) Linux
在Linux系統(tǒng)中,每個進程都有獨立的虛擬內(nèi)存空間,也就是說不同的進程訪問同一段虛擬內(nèi)存地址所得到的數(shù)據(jù)是不一樣的,這是因為不同進程相同的虛擬內(nèi)存地址會映射到不同的物理內(nèi)存地址上。

[[427282]]

在Linux系統(tǒng)中,每個進程都有獨立的虛擬內(nèi)存空間,也就是說不同的進程訪問同一段虛擬內(nèi)存地址所得到的數(shù)據(jù)是不一樣的,這是因為不同進程相同的虛擬內(nèi)存地址會映射到不同的物理內(nèi)存地址上。

但有時候為了讓不同進程之間進行通信,需要讓不同進程共享相同的物理內(nèi)存,Linux通過 共享內(nèi)存 來實現(xiàn)這個功能。下面先來介紹一下Linux系統(tǒng)的共享內(nèi)存的使用。

共享內(nèi)存使用

1. 獲取共享內(nèi)存

要使用共享內(nèi)存,首先需要使用 shmget() 函數(shù)獲取共享內(nèi)存,shmget() 函數(shù)的原型如下: 

  1. int shmget(key_t key, size_t sizeint shmflg); 
  • 參數(shù) key 一般由 ftok() 函數(shù)生成,用于標識系統(tǒng)的唯一IPC資源。
  • 參數(shù) size 指定創(chuàng)建的共享內(nèi)存大小。
  • 參數(shù) shmflg 指定 shmget() 函數(shù)的動作,比如傳入 IPC_CREAT 表示要創(chuàng)建新的共享內(nèi)存。

函數(shù)調(diào)用成功時返回一個新建或已經(jīng)存在的的共享內(nèi)存標識符,取決于shmflg的參數(shù)。失敗返回-1,并設置錯誤碼。

2. 關聯(lián)共享內(nèi)存

shmget() 函數(shù)返回的是一個標識符,而不是可用的內(nèi)存地址,所以還需要調(diào)用 shmat() 函數(shù)把共享內(nèi)存關聯(lián)到某個虛擬內(nèi)存地址上。shmat() 函數(shù)的原型如下: 

  1. void *shmat(int shmid, const void *shmaddr, int shmflg); 
  • 參數(shù) shmid 是 shmget() 函數(shù)返回的標識符。
  • 參數(shù) shmaddr 是要關聯(lián)的虛擬內(nèi)存地址,如果傳入0,表示由系統(tǒng)自動選擇合適的虛擬內(nèi)存地址。
  • 參數(shù) shmflg 若指定了 SHM_RDONLY 位,則以只讀方式連接此段,否則以讀寫方式連接此段。

函數(shù)調(diào)用成功返回一個可用的指針(虛擬內(nèi)存地址),出錯返回-1。

3. 取消關聯(lián)共享內(nèi)存

當一個進程不需要共享內(nèi)存的時候,就需要取消共享內(nèi)存與虛擬內(nèi)存地址的關聯(lián)。取消關聯(lián)共享內(nèi)存通過 shmdt() 函數(shù)實現(xiàn),原型如下: 

  1. int shmdt(const void *shmaddr); 

參數(shù) shmaddr 是要取消關聯(lián)的虛擬內(nèi)存地址,也就是 shmat() 函數(shù)返回的值。

函數(shù)調(diào)用成功返回0,出錯返回-1。

共享內(nèi)存使用例子

下面通過一個例子來介紹一下共享內(nèi)存的使用方法。在這個例子中,有兩個進程,分別為 進程A 和 進程B,進程A 創(chuàng)建一塊共享內(nèi)存,然后寫入數(shù)據(jù),進程B 獲取這塊共享內(nèi)存并且讀取其內(nèi)容。

進程A

  1. #include <stdio.h> 
  2. #include <unistd.h> 
  3. #include <sys/types.h> 
  4. #include <sys/ipc.h> 
  5. #include <sys/shm.h> 
  6.  
  7. #define SHM_PATH "/tmp/shm" 
  8. #define SHM_SIZE 128 
  9.  
  10. int main(int argc, char *argv[]) 
  11.     int shmid; 
  12.     char *addr; 
  13.     key_t key = ftok(SHM_PATH, 0x6666); 
  14.      
  15.     shmid = shmget(key, SHM_SIZE, IPC_CREAT|IPC_EXCL|0666); 
  16.     if (shmid < 0) { 
  17.         printf("failed to create share memory\n"); 
  18.         return -1; 
  19.     } 
  20.      
  21.     addr = shmat(shmid, NULL, 0); 
  22.     if (addr <= 0) { 
  23.         printf("failed to map share memory\n"); 
  24.         return -1; 
  25.     } 
  26.      
  27.     sprintf(addr, "%s""Hello World\n"); 
  28.      
  29.     return 0; 

進程B

  1. #include <stdio.h> 
  2. #include <string.h> 
  3. #include <unistd.h> 
  4. #include <sys/types.h> 
  5. #include <sys/ipc.h> 
  6. #include <sys/shm.h> 
  7.  
  8. #define SHM_PATH "/tmp/shm" 
  9. #define SHM_SIZE 128 
  10.  
  11. int main(int argc, char *argv[]) 
  12.     int shmid; 
  13.     char *addr; 
  14.     key_t key = ftok(SHM_PATH, 0x6666); 
  15.      
  16.     char buf[128]; 
  17.      
  18.     shmid = shmget(key, SHM_SIZE, IPC_CREAT); 
  19.     if (shmid < 0) { 
  20.         printf("failed to get share memory\n"); 
  21.         return -1; 
  22.     } 
  23.      
  24.     addr = shmat(shmid, NULL, 0); 
  25.     if (addr <= 0) { 
  26.         printf("failed to map share memory\n"); 
  27.         return -1; 
  28.     } 
  29.      
  30.     strcpy(buf, addr, 128); 
  31.     printf("%s", buf); 
  32.      
  33.     return 0; 

測試時先運行進程A,然后再運行進程B,可以看到進程B會打印出 “Hello World”,說明共享內(nèi)存已經(jīng)創(chuàng)建成功并且讀取。

共享內(nèi)存實現(xiàn)原理

我們先通過一幅圖來了解一下共享內(nèi)存的大概原理,如下圖: 

 

通過上圖可知,共享內(nèi)存是通過將不同進程的虛擬內(nèi)存地址映射到相同的物理內(nèi)存地址來實現(xiàn)的,下面將會介紹Linux的實現(xiàn)方式。

在Linux內(nèi)核中,每個共享內(nèi)存都由一個名為 struct shmid_kernel 的結(jié)構(gòu)體來管理,而且Linux限制了系統(tǒng)最大能創(chuàng)建的共享內(nèi)存為128個。通過類型為 struct shmid_kernel 結(jié)構(gòu)的數(shù)組來管理,如下: 

  1. struct shmid_ds { 
  2.  struct ipc_perm  shm_perm; /* operation perms */ 
  3.  int   shm_segsz; /* size of segment (bytes) */ 
  4.  __kernel_time_t  shm_atime; /* last attach time */ 
  5.  __kernel_time_t  shm_dtime; /* last detach time */ 
  6.  __kernel_time_t  shm_ctime; /* last change time */ 
  7.  __kernel_ipc_pid_t shm_cpid; /* pid of creator */ 
  8.  __kernel_ipc_pid_t shm_lpid; /* pid of last operator */ 
  9.  unsigned short  shm_nattch; /* noof current attaches */ 
  10.  unsigned short   shm_unused; /* compatibility */ 
  11.  void    *shm_unused2; /* ditto - used by DIPC */ 
  12.  void   *shm_unused3; /* unused */ 
  13. }; 
  14.  
  15. struct shmid_kernel 
  16. {  
  17.  struct shmid_ds  u; 
  18.  /* the following are private */ 
  19.  unsigned long  shm_npages; /* size of segment (pages) */ 
  20.  pte_t   *shm_pages; /* array of ptrs to frames -> SHMMAX */  
  21.  struct vm_area_struct *attaches; /* descriptors for attaches */ 
  22. }; 
  23.  
  24. static struct shmid_kernel *shm_segs[SHMMNI]; // SHMMNI等于128 

從注釋可以知道 struct shmid_kernel 結(jié)構(gòu)體各個字段的作用,比如 shm_npages 字段表示共享內(nèi)存使用了多少個內(nèi)存頁。而 shm_pages 字段指向了共享內(nèi)存映射的虛擬內(nèi)存頁表項數(shù)組等。

另外 struct shmid_ds 結(jié)構(gòu)體用于管理共享內(nèi)存的信息,而 shm_segs數(shù)組 用于管理系統(tǒng)中所有的共享內(nèi)存。

shmget() 函數(shù)實現(xiàn)

通過前面的例子可知,要使用共享內(nèi)存,首先需要調(diào)用 shmget() 函數(shù)來創(chuàng)建或者獲取一塊共享內(nèi)存。shmget() 函數(shù)的實現(xiàn)如下: 

  1. asmlinkage long sys_shmget (key_t keyint sizeint shmflg) 
  2.  struct shmid_kernel *shp; 
  3.  int err, id = 0; 
  4.  
  5.  down(&current->mm->mmap_sem); 
  6.  spin_lock(&shm_lock); 
  7.  if (size < 0 || size > shmmax) { 
  8.   err = -EINVAL; 
  9.  } else if (key == IPC_PRIVATE) { 
  10.   err = newseg(key, shmflg, size); 
  11.  } else if ((id = findkey (key)) == -1) { 
  12.   if (!(shmflg & IPC_CREAT)) 
  13.    err = -ENOENT; 
  14.   else 
  15.    err = newseg(key, shmflg, size); 
  16.  } else if ((shmflg & IPC_CREAT) && (shmflg & IPC_EXCL)) { 
  17.   err = -EEXIST; 
  18.  } else { 
  19.   shp = shm_segs[id]; 
  20.   if (shp->u.shm_perm.mode & SHM_DEST) 
  21.    err = -EIDRM; 
  22.   else if (size > shp->u.shm_segsz) 
  23.    err = -EINVAL; 
  24.   else if (ipcperms (&shp->u.shm_perm, shmflg)) 
  25.    err = -EACCES; 
  26.   else 
  27.    err = (int) shp->u.shm_perm.seq * SHMMNI + id; 
  28.  } 
  29.  spin_unlock(&shm_lock); 
  30.  up(&current->mm->mmap_sem); 
  31.  return err; 

shmget() 函數(shù)的實現(xiàn)比較簡單,首先調(diào)用 findkey() 函數(shù)查找值為key的共享內(nèi)存是否已經(jīng)被創(chuàng)建,findkey() 函數(shù)返回共享內(nèi)存在 shm_segs數(shù)組 的索引。如果找到,那么直接返回共享內(nèi)存的標識符即可。否則就調(diào)用 newseg() 函數(shù)創(chuàng)建新的共享內(nèi)存。newseg() 函數(shù)的實現(xiàn)也比較簡單,就是創(chuàng)建一個新的 struct shmid_kernel 結(jié)構(gòu)體,然后設置其各個字段的值,并且保存到 shm_segs數(shù)組 中。

shmat() 函數(shù)實現(xiàn)

shmat() 函數(shù)用于將共享內(nèi)存映射到本地虛擬內(nèi)存地址,由于 shmat() 函數(shù)的實現(xiàn)比較復雜,所以我們分段來分析這個函數(shù): 

  1. asmlinkage long sys_shmat (int shmid, char *shmaddr, int shmflg, ulong *raddr) 
  2.  struct shmid_kernel *shp; 
  3.  struct vm_area_struct *shmd; 
  4.  int err = -EINVAL; 
  5.  unsigned int id; 
  6.  unsigned long addr; 
  7.  unsigned long len; 
  8.  
  9.  down(&current->mm->mmap_sem); 
  10.  spin_lock(&shm_lock); 
  11.  if (shmid < 0) 
  12.   goto out
  13.  
  14.  shp = shm_segs[id = (unsigned int) shmid % SHMMNI]; 
  15.  if (shp == IPC_UNUSED || shp == IPC_NOID) 
  16.   goto out

上面這段代碼主要通過 shmid 標識符來找到共享內(nèi)存描述符,上面說過系統(tǒng)中所有的共享內(nèi)存到保存在 shm_segs 數(shù)組中。 

  1. if (!(addr = (ulong) shmaddr)) { 
  2.  if (shmflg & SHM_REMAP) 
  3.   goto out
  4.  err = -ENOMEM; 
  5.  addr = 0; 
  6. again: 
  7.  if (!(addr = get_unmapped_area(addr, shp->u.shm_segsz))) // 獲取一個空閑的虛擬內(nèi)存空間 
  8.   goto out
  9.  if(addr & (SHMLBA - 1)) { 
  10.   addr = (addr + (SHMLBA - 1)) & ~(SHMLBA - 1); 
  11.   goto again; 
  12.  } 
  13. else if (addr & (SHMLBA-1)) { 
  14.  if (shmflg & SHM_RND) 
  15.   addr &= ~(SHMLBA-1);       /* round down */ 
  16.  else 
  17.   goto out

上面的代碼主要找到一個可用的虛擬內(nèi)存地址,如果在調(diào)用 shmat() 函數(shù)時沒有指定了虛擬內(nèi)存地址,那么就通過 get_unmapped_area() 函數(shù)來獲取一個可用的虛擬內(nèi)存地址。 

  1. spin_unlock(&shm_lock); 
  2.  err = -ENOMEM; 
  3.  shmd = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL); 
  4.  spin_lock(&shm_lock); 
  5.  if (!shmd) 
  6.   goto out
  7.  if ((shp != shm_segs[id]) || (shp->u.shm_perm.seq != (unsigned int) shmid / SHMMNI)) { 
  8.   kmem_cache_free(vm_area_cachep, shmd); 
  9.   err = -EIDRM; 
  10.   goto out
  11.  } 

上面的代碼主要通過調(diào)用 kmem_cache_alloc() 函數(shù)創(chuàng)建一個 vm_area_struct 結(jié)構(gòu),在內(nèi)存管理一章知道,vm_area_struct 結(jié)構(gòu)用于管理進程的虛擬內(nèi)存空間。 

  1. shmd->vm_private_data = shm_segs + id; 
  2.  shmd->vm_start = addr; 
  3.  shmd->vm_end = addr + shp->shm_npages * PAGE_SIZE; 
  4.  shmd->vm_mm = current->mm; 
  5.  shmd->vm_page_prot = (shmflg & SHM_RDONLY) ? PAGE_READONLY : PAGE_SHARED; 
  6.  shmd->vm_flags = VM_SHM | VM_MAYSHARE | VM_SHARED 
  7.     | VM_MAYREAD | VM_MAYEXEC | VM_READ | VM_EXEC 
  8.     | ((shmflg & SHM_RDONLY) ? 0 : VM_MAYWRITE | VM_WRITE); 
  9.  shmd->vm_file = NULL
  10.  shmd->vm_offset = 0; 
  11.  shmd->vm_ops = &shm_vm_ops; 
  12.  
  13.  shp->u.shm_nattch++;     /* prevent destruction */ 
  14.  spin_unlock(&shm_lock); 
  15.  err = shm_map(shmd); 
  16.  spin_lock(&shm_lock); 
  17.  if (err) 
  18.   goto failed_shm_map; 
  19.  
  20.  insert_attach(shp,shmd);  /* insert shmd into shp->attaches */ 
  21.  
  22.  shp->u.shm_lpid = current->pid; 
  23.  shp->u.shm_atime = CURRENT_TIME
  24.  
  25.  *raddr = addr; 
  26.  err = 0; 
  27. out
  28.  spin_unlock(&shm_lock); 
  29.  up(&current->mm->mmap_sem); 
  30.  return err; 
  31.  ... 

上面的代碼主要是設置剛創(chuàng)建的 vm_area_struct 結(jié)構(gòu)的各個字段,比較重要的是設置其 vm_ops 字段為 shm_vm_ops,shm_vm_ops 定義如下: 

  1. static struct vm_operations_struct shm_vm_ops = { 
  2.  shm_open,  /* open - callback for a new vm-area open */ 
  3.  shm_close,  /* close - callback for when the vm-area is released */ 
  4.  NULL,   /* no need to sync pages at unmap */ 
  5.  NULL,   /* protect */ 
  6.  NULL,   /* sync */ 
  7.  NULL,   /* advise */ 
  8.  shm_nopage,  /* nopage */ 
  9.  NULL,   /* wppage */ 
  10.  shm_swapout  /* swapout */ 
  11. }; 

shm_vm_ops 的 nopage 回調(diào)為 shm_nopage() 函數(shù),也就是說,當發(fā)生頁缺失異常時將會調(diào)用此函數(shù)來恢復內(nèi)存的映射。

從上面的代碼可看出,shmat() 函數(shù)只是申請了進程的虛擬內(nèi)存空間,而共享內(nèi)存的物理空間并沒有申請,那么在什么時候申請物理內(nèi)存呢?答案就是當進程發(fā)生缺頁異常的時候會調(diào)用 shm_nopage() 函數(shù)來恢復進程的虛擬內(nèi)存地址到物理內(nèi)存地址的映射。

shm_nopage() 函數(shù)實現(xiàn)

shm_nopage() 函數(shù)是當發(fā)生內(nèi)存缺頁異常時被調(diào)用的,代碼如下: 

  1. tatic struct page * shm_nopage(struct vm_area_struct * shmd, unsigned long address, int no_share) 
  2.  pte_t pte; 
  3.  struct shmid_kernel *shp; 
  4.  unsigned int idx; 
  5.  struct page * page; 
  6.  
  7.  shp = *(struct shmid_kernel **) shmd->vm_private_data; 
  8.  idx = (address - shmd->vm_start + shmd->vm_offset) >> PAGE_SHIFT; 
  9.  
  10.  spin_lock(&shm_lock); 
  11. again: 
  12.  pte = shp->shm_pages[idx]; // 共享內(nèi)存的頁表項 
  13.  if (!pte_present(pte)) {   // 如果內(nèi)存頁不存在 
  14.   if (pte_none(pte)) { 
  15.    spin_unlock(&shm_lock); 
  16.    page = get_free_highpage(GFP_HIGHUSER); // 申請一個新的物理內(nèi)存頁 
  17.    if (!page) 
  18.     goto oom; 
  19.    clear_highpage(page); 
  20.    spin_lock(&shm_lock); 
  21.    if (pte_val(pte) != pte_val(shp->shm_pages[idx])) 
  22.     goto changed; 
  23.   } else { 
  24.    ... 
  25.   } 
  26.   shm_rss++; 
  27.   pte = pte_mkdirty(mk_pte(page, PAGE_SHARED));   // 創(chuàng)建頁表項 
  28.   shp->shm_pages[idx] = pte;                      // 保存共享內(nèi)存的頁表項 
  29.  } else 
  30.   --current->maj_flt;  /* was incremented in do_no_page */ 
  31.  
  32. done: 
  33.  get_page(pte_page(pte)); 
  34.  spin_unlock(&shm_lock); 
  35.  current->min_flt++; 
  36.  return pte_page(pte); 
  37.  ... 

shm_nopage() 函數(shù)的主要功能是當發(fā)生內(nèi)存缺頁時,申請新的物理內(nèi)存頁,并映射到共享內(nèi)存中。由于使用共享內(nèi)存時會映射到相同的物理內(nèi)存頁上,從而不同進程可以共用此塊內(nèi)存。  

 

責任編輯:龐桂玉 來源: 良許Linux
相關推薦

2024-01-09 08:24:47

JMM核心線程

2024-03-26 00:33:59

JVM內(nèi)存對象

2021-10-25 16:01:01

Linux設備樹字符串

2021-08-31 07:02:34

數(shù)據(jù)響應Vue偵測數(shù)據(jù)變化

2021-05-12 18:22:36

Linux 內(nèi)存管理

2025-04-09 05:22:00

2021-03-28 18:40:02

LinuxWindowsJava

2021-08-13 05:50:01

ContainerdDockerKubernetes

2023-12-15 15:55:24

Linux線程同步

2019-09-23 10:51:14

JavaJava虛擬機Linux

2021-04-30 19:53:53

HugePages大內(nèi)存頁物理

2022-08-17 18:25:37

Java分布式搜索引擎

2021-08-31 07:02:20

Diff算法DOM

2021-10-20 07:18:51

Linux延時隊列

2020-10-29 08:55:04

微服務

2023-09-08 08:20:46

ThreadLoca多線程工具

2020-01-14 12:08:32

內(nèi)存安全

2025-04-07 03:02:00

電腦內(nèi)存數(shù)據(jù)

2021-04-24 09:02:36

Linux 內(nèi)存分配

2021-08-01 08:05:39

Linux信號原理
點贊
收藏

51CTO技術(shù)棧公眾號