如何在C语言中的Linux中使用共享内存


117

我的一个项目有一个问题。

我一直在尝试找到一个有据可查的使用共享内存的例子,fork()但是没有成功。

基本上情况是,当用户启动程序时,我需要在共享内存中存储两个值:current_path(它是一个char *)file_name(它也是char *)

根据命令参数,将启动一个新进程fork(),该进程需要读取和修改共享内存中存储的current_path变量,而file_name变量为只读。

是否有关于共享内存的很好的教程,并带有示例代码(如果可能),您可以将其引导至?


1
您可以考虑使用线程而不是进程。然后,整个内存将共享,而无需任何其他技巧。
elomage 2014年

下面的答案讨论了System V IPC机制,shmget()等等。以及(aka )的纯mmap()方法-尽管POSIX未定义。还有POSIX ,用于管理共享内存对象。[…续…]MAP_ANONMAP_ANONYMOUSMAP_ANONshm_open()shm_close()
乔纳森·莱夫勒

[…continuation…]这些具有与System V IPC共享内存相同的优点-共享内存对象可以在创建它的进程的生命周期内保留(直到某些进程执行shm_unlink()),而使用mmap()该机制的机制需要文件并MAP_SHARED保留数据(并MAP_ANON排除持久性)。规范的“原理”部分中有一个完整的示例shm_open()
乔纳森·莱夫勒

Answers:


164

有两种方法:shmgetmmap。我将讨论mmap,因为它更现代,更灵活,但是如果您想使用旧式工具,可以看看man shmget或本教程)。

mmap()功能可用于分配具有高度可自定义参数的内存缓冲区,以控制访问和权限,并在必要时通过文件系统存储支持它们。

以下函数创建一个内存缓冲,进程可以与其子进程共享该缓冲区:

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

void* create_shared_memory(size_t size) {
  // Our memory buffer will be readable and writable:
  int protection = PROT_READ | PROT_WRITE;

  // The buffer will be shared (meaning other processes can access it), but
  // anonymous (meaning third-party processes cannot obtain an address for it),
  // so only this process and its children will be able to use it:
  int visibility = MAP_SHARED | MAP_ANONYMOUS;

  // The remaining parameters to `mmap()` are not important for this use case,
  // but the manpage for `mmap` explains their purpose.
  return mmap(NULL, size, protection, visibility, -1, 0);
}

下面是一个示例程序,该程序使用上面定义的功能来分配缓冲区。父进程将编写一条消息,进行分叉,然后等待其子进程修改缓冲区。这两个进程都可以读取和写入共享内存。

#include <string.h>
#include <unistd.h>

int main() {
  char parent_message[] = "hello";  // parent process will write this message
  char child_message[] = "goodbye"; // child process will then write this one

  void* shmem = create_shared_memory(128);

  memcpy(shmem, parent_message, sizeof(parent_message));

  int pid = fork();

  if (pid == 0) {
    printf("Child read: %s\n", shmem);
    memcpy(shmem, child_message, sizeof(child_message));
    printf("Child wrote: %s\n", shmem);

  } else {
    printf("Parent read: %s\n", shmem);
    sleep(1);
    printf("After 1s, parent read: %s\n", shmem);
  }
}

51
这就是为什么Linux对于没有经验的开发人员如此令人沮丧的原因。手册页没有解释如何实际使用它,也没有示例代码。:(
bleepzter 2011年

46
哈哈,我知道您的意思,但这实际上是因为我们不习惯阅读手册。当我学会阅读并习惯它们时,它们变得比带有特定演示的糟糕教程更加有用。我记得我在操作系统课程中获得了10/10的成绩,但在考试期间仅使用手册页作为参考。
slezica 2011年

18
shmget这是一种非常老式的方法,有些人会说它已经过时了,它可以做共享内存...最好使用mmapshm_open,使用普通文件,或者简单地使用MAP_ANONYMOUS
R .. GitHub停止帮助ICE,

4
@Mark @R你们是正确的,我会在答案中指出这一点,以供将来参考。
slezica 2011年

4
好吧,由于某种原因,这个答案很受欢迎,所以我决定值得一读。只用了4年
slezica '17

26

这是共享内存的示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_SIZE 1024  /* make it a 1K shared memory segment */

int main(int argc, char *argv[])
{
    key_t key;
    int shmid;
    char *data;
    int mode;

    if (argc > 2) {
        fprintf(stderr, "usage: shmdemo [data_to_write]\n");
        exit(1);
    }

    /* make the key: */
    if ((key = ftok("hello.txt", 'R')) == -1) /*Here the file must exist */ 
{
        perror("ftok");
        exit(1);
    }

    /*  create the segment: */
    if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
        perror("shmget");
        exit(1);
    }

    /* attach to the segment to get a pointer to it: */
    data = shmat(shmid, NULL, 0);
    if (data == (char *)(-1)) {
        perror("shmat");
        exit(1);
    }

    /* read or modify the segment, based on the command line: */
    if (argc == 2) {
        printf("writing to segment: \"%s\"\n", argv[1]);
        strncpy(data, argv[1], SHM_SIZE);
    } else
        printf("segment contains: \"%s\"\n", data);

    /* detach from the segment: */
    if (shmdt(data) == -1) {
        perror("shmdt");
        exit(1);
    }

    return 0;
}

脚步 :

  1. 使用ftok将路径名和项目标识符转换为System V IPC密钥

  2. 使用shmget分配共享的内存段

  3. 使用shmat将shmid标识的共享内存段附加到调用进程的地址空间

  4. 在存储区上进行操作

  5. 使用shmdt分离


6
为什么将0强制转换为void *而不是使用NULL?
佩雷(ClémentPéau)

但是,此代码无法处理共享内存的删除。程序退出后,必须通过ipcrm -m 0手动将其删除
。– bumfo

12

这些包括使用共享内存

#include<sys/ipc.h>
#include<sys/shm.h>

int shmid;
int shmkey = 12222;//u can choose it as your choice

int main()
{
  //now your main starting
  shmid = shmget(shmkey,1024,IPC_CREAT);
  // 1024 = your preferred size for share memory
  // IPC_CREAT  its a flag to create shared memory

  //now attach a memory to this share memory
  char *shmpointer = shmat(shmid,NULL);

  //do your work with the shared memory 
  //read -write will be done with the *shmppointer
  //after your work is done deattach the pointer

  shmdt(&shmpointer, NULL);

8

试试这个代码示例,我对其进行了测试,来源:http : //www.makelinux.net/alp/035

#include <stdio.h> 
#include <sys/shm.h> 
#include <sys/stat.h> 

int main () 
{
  int segment_id; 
  char* shared_memory; 
  struct shmid_ds shmbuffer; 
  int segment_size; 
  const int shared_segment_size = 0x6400; 

  /* Allocate a shared memory segment.  */ 
  segment_id = shmget (IPC_PRIVATE, shared_segment_size, 
                 IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR); 
  /* Attach the shared memory segment.  */ 
  shared_memory = (char*) shmat (segment_id, 0, 0); 
  printf ("shared memory attached at address %p\n", shared_memory); 
  /* Determine the segment's size. */ 
  shmctl (segment_id, IPC_STAT, &shmbuffer); 
  segment_size  =               shmbuffer.shm_segsz; 
  printf ("segment size: %d\n", segment_size); 
  /* Write a string to the shared memory segment.  */ 
  sprintf (shared_memory, "Hello, world."); 
  /* Detach the shared memory segment.  */ 
  shmdt (shared_memory); 

  /* Reattach the shared memory segment, at a different address.  */ 
  shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0); 
  printf ("shared memory reattached at address %p\n", shared_memory); 
  /* Print out the string from shared memory.  */ 
  printf ("%s\n", shared_memory); 
  /* Detach the shared memory segment.  */ 
  shmdt (shared_memory); 

  /* Deallocate the shared memory segment.  */ 
  shmctl (segment_id, IPC_RMID, 0); 

  return 0; 
} 

2
这是很好的代码,除了我不认为它显示了客户端如何访问共享内存段(通过使用shmgetshmat来自不同的进程),这是共享内存的全部方面……=(
étale-cohomology17年

7

这是一个mmap示例:

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/*
 * pvtmMmapAlloc - creates a memory mapped file area.  
 * The return value is a page-aligned memory value, or NULL if there is a failure.
 * Here's the list of arguments:
 * @mmapFileName - the name of the memory mapped file
 * @size - the size of the memory mapped file (should be a multiple of the system page for best performance)
 * @create - determines whether or not the area should be created.
 */
void* pvtmMmapAlloc (char * mmapFileName, size_t size, char create)  
{      
  void * retv = NULL;                                                                                              
  if (create)                                                                                         
  {                                                                                                   
    mode_t origMask = umask(0);                                                                       
    int mmapFd = open(mmapFileName, O_CREAT|O_RDWR, 00666);                                           
    umask(origMask);                                                                                  
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      perror("open mmapFd failed");                                                                   
      return NULL;                                                                                    
    }                                                                                                 
    if ((ftruncate(mmapFd, size) == 0))               
    {                                                                                                 
      int result = lseek(mmapFd, size - 1, SEEK_SET);               
      if (result == -1)                                                                               
      {                                                                                               
        perror("lseek mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               

      /* Something needs to be written at the end of the file to                                      
       * have the file actually have the new size.                                                    
       * Just writing an empty string at the current file position will do.                           
       * Note:                                                                                        
       *  - The current position in the file is at the end of the stretched                           
       *    file due to the call to lseek().  
              *  - The current position in the file is at the end of the stretched                    
       *    file due to the call to lseek().                                                          
       *  - An empty string is actually a single '\0' character, so a zero-byte                       
       *    will be written at the last byte of the file.                                             
       */                                                                                             
      result = write(mmapFd, "", 1);                                                                  
      if (result != 1)                                                                                
      {                                                                                               
        perror("write mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
      retv  =  mmap(NULL, size,   
                  PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                     

      if (retv == MAP_FAILED || retv == NULL)                                                         
      {                                                                                               
        perror("mmap");                                                                               
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
    }                                                                                                 
  }                                                                                                   
  else                                                                                                
  {                                                                                                   
    int mmapFd = open(mmapFileName, O_RDWR, 00666);                                                   
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      return NULL;                                                                                    
    }                                                                                                 
    int result = lseek(mmapFd, 0, SEEK_END);                                                          
    if (result == -1)                                                                                 
    {                                                                                                 
      perror("lseek mmapFd failed");                  
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 
    if (result == 0)                                                                                  
    {                                                                                                 
      perror("The file has 0 bytes");                           
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                              
    retv  =  mmap(NULL, size,     
                PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                       

    if (retv == MAP_FAILED || retv == NULL)                                                           
    {                                                                                                 
      perror("mmap");                                                                                 
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 

    close(mmapFd);                                                                                    

  }                                                                                                   
  return retv;                                                                                        
}                                                                                                     

open添加文件I / O开销。使用shm_open代替。
osvein

1
@Spookbuster,在shm_open的某些实现中,在幕后调用了open(),所以我不得不不同意您的评估;这是一个示例:code.woboq.org/userspace/glibc/sysdeps/posix/shm_open.c.html
Leo

虽然某些shm_open()实现在后台使用open(),但POSIX对shm_open()生成的文件描述符的要求较低。例如,不需要实现为shm_open()文件描述符支持I / O功能(如read()和write()),从而允许某些实现对open()无法实现的shm_open()进行优化。如果您要做的只是mmap(),则应使用shm_open()。
osvein

大多数Linux-glibc安装程序都使用tmpfs支持shm_open()来进行这样的优化。虽然通常可以通过open()访问相同的tmpfs,但没有可移植的方式来了解其路径。shm_open()让您以可移植的方式使用该优化。POSIX使shm_open()的性能比open()更好。并非所有的实现都将利用这种潜力,但是它的性能不会比open()差。但是我同意我声称open()总是增加开销的说法太广泛了。
osvein
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.