Read string from shared memory C++ POSIX

偶尔善良 提交于 2021-01-28 05:05:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!