[英]Read string from shared memory C++ POSIX
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
. 但当我试图接收这个数据程序时,说
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(...);
). 我也尝试将其重写为
char *
但它也不起作用( char *line = (char *)shmat(...);
)。
You cannot place an std::string
on shared memory; 你不能在共享内存上放置一个
std::string
; 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 (eg maybe see here ): C ++委员会在某种程度上设想你应该能够使用一个使用相对指针的共享内存分配器(例如,可能会在这里看到 ):
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 .)
(我认为这是LWG 1521. )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.