#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;
}
我从共享内存教程中获得了代码。它一直有效,直到我定义了 struct LOCK 并尝试将 LOCK 而不是 char* 写入共享内存。
有人可以帮我找出导致分段错误的问题吗?
您正在放置vector
s and string
s 到共享内存中。这两个类都分配自己的内存,这些内存将在生成分配的任何进程的地址空间内分配,并且在从其他进程访问时会产生段错误。您可以尝试指定分配器来使用该共享内存,但由于在 C++03 中分配器被假定为无状态,所以我不确定这是否可能。
考虑看看 Boost.Interprocess 是如何做到的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)