从共享内存 C++ POSIX 读取字符串 [英] Read string from shared memory C++ POSIX

查看:89
本文介绍了从共享内存 C++ POSIX 读取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的另一个问题中,一位用户帮助我通过共享内存发送字符串.但是当我尝试接收这个数据时,程序说Core dumped.我试试这个代码:

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);
}

我也尝试将其重写为 char * 但它也不起作用(char *line = (char *)shmat(...);).>

I tried also rewrite this to char * but it not working too (char *line = (char *)shmat(...);).

推荐答案

你不能在共享内存上放置std::string;该对象内部存储的指针在运行进程之外没有意义.

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.

C++ 委员会在某个时候设想你应该能够使用一个使用相对指针的共享内存分配器(例如,也许 见这里):

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>>

然而,这受到标准库实现的未指定性质的阻碍;该标准实际上并没有强制要求使用分配器的标准库类也在内部使用分配器指针.(我认为这是 LWG 1521.)

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.)

这篇关于从共享内存 C++ POSIX 读取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆