问题
In my other question one user help me with send string by shared memory. But when I try to receive this data program says Core dumped
. I try this code:
key_t lineKey = ftok("/tmp", '1');
int sharedLine = shmget(lineKey, sizeof(std::string), IPC_CREAT | 0666);
std::string *line = (std::string *)shmat(sharedLine, NULL, 0);
sem_t *reader1_sem;
reader1_sem = sem_open("reader1_sem", O_CREAT, 0666, 0);
while (1) {
sem_wait(reader1_sem);
std::cout << (*line);
}
I tried also rewrite this to char *
but it not working too (char *line = (char *)shmat(...);
).
回答1:
You cannot place an std::string
on shared memory; The pointers that are stored internally in this object are not meaningful outside the running process.
The C++ committee envisioned at some point that you ought to be able to use a shared-memory allocator that would use relative pointers (e.g. maybe see here):
std::basic_string<char, std::char_traits<char>, magic_allocator<char>>
However, this is hampered by the unspecified nature of standard library implementations; the Standard does not actually mandate that standard library classes that use allocators also use allocator pointers internally. (I think this is LWG 1521.)
来源:https://stackoverflow.com/questions/34582558/read-string-from-shared-memory-c-posix