在linux上编写的一个简单的C++共享内存程序:分段错误

Ter*_* Li 7 c++ linux shared-memory segmentation-fault

#include <stdio.h> 
#include <sys/shm.h> 
#include <sys/stat.h> 
#include <string>
#include <vector>
#include <iostream>

using namespace std;

struct LOCK {
  string name;
  string type;
  vector <string> pids;
};

int main () 

{

  int segment_id; 

  LOCK* 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 = (LOCK*) 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."); 
  shared_memory -> name = "task 1";
  shared_memory -> type = "read";
  (shared_memory -> pids).push_back("12345");
  (shared_memory -> pids).push_back("67890");

  /* Detach the shared memory segment.  */ 

  shmdt (shared_memory); 



  /* Reattach the shared memory segment, at a different address.  */ 

  shared_memory = (LOCK*) 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 -> name); 
  cout << "Name of the shared memory: " + shared_memory -> name << endl;

  /* Detach the shared memory segment.  */ 

  shmdt (shared_memory); 



  /* Deallocate the shared memory segment.  */ 

  shmctl (segment_id, IPC_RMID, 0); 



  return 0; 

} 
Run Code Online (Sandbox Code Playgroud)

我从共享内存教程中获取了代码.它一直工作,直到我定义了struct LOCK并尝试将LOCK而不是char*写入共享内存.

有人可以帮我解决导致分段错误的问题吗?

K-b*_*llo 11

您将vectors和strings放入共享内存中.这两个类都分配自己的内存,这些内存将在任何进程生成分配的地址空间内分配,并在从其他进程访问时产生段错误.您可以尝试指定分配器使用该共享内存,但由于在C++ 03中假定分配器是无状态的,我不确定它是否可行.

考虑一下Boost.Interprocess是如何做到的.

  • @TamásSzelei号怎么可能?如果在地址X处映射共享内存,则指向其中对象的指针将为X + A(其中A是相对偏移量).如果另一个进程映射了地址Y处的共享内存(因为X在该进程中使用,或者只是运气不好),它需要一个指向Y + A的指针来访问相同的数据.您不能将绝对指针(X + A)从一个进程传递到另一个进程或将其放在共享内存中.您必须传递相对指针(A),并且每个进程需要在其取消引用之前将其基本映射地址添加到指针. (2认同)