gpt4 book ai didi

c++ - std::string 的共享内存给出段错误 (linux)

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:27:49 24 4
gpt4 key购买 nike

我目前正在尝试将 put 结构放在 linux 上 2 个进程之间的共享内存中。我在共享 bool 或 int 时没有问题,但在尝试共享字符串、std::string 或 char 时出现段错误。

现在我的代码是:

#include <iostream>
#include <sys/types.h> //shmat
#include <sys/shm.h>
#include <sys/stat.h> //open
#include <fcntl.h>
#include <unistd.h> //close

using namespace std;

struct Prises{

int numero;
int transactionId;
bool reservation;
bool charge;
bool disponibilite;
bool defaut;
bool verrouillage;
bool trappe;
int LEDverte;
int LEDrouge;
std::string carte;
std::string etat;

};

int main()
{
const char *keyFile = "/tmp/key.dat";
/* Make sure the file exists. */
int descriptor = open(keyFile, O_CREAT | O_RDWR, S_IRWXU);

/* Only wanted to make sure that the file exists. */
close(descriptor);

/* Generate memory key. */
key_t sharedKey = ftok(keyFile, 1);

/* Get the shared memory segment id. Note we include
the permissions. */
int sharedSpaceId = shmget(sharedKey, 2*sizeof(Prises),
IPC_CREAT | S_IRUSR | S_IWUSR);

/* Attach the shared memory segment. */
Prises *PrisesArray = (Prises *) shmat(sharedSpaceId, NULL, 0);

PrisesArray[1].defaut=true;
PrisesArray[2].defaut=false;

int ok;
std::cin>>ok;
return 0;
}

在此示例中,从 2 个结构共享 2 个 bool 效果很好,但如果我尝试输入数据或从 std::string (etat, carte) 读取数据,如下所示:

PrisesArray[1].etat="hello";

它在调试时给我一个段错误(并且清除在发布时不起作用),我尝试使用简单的字符串和字符(甚至一个字符),它仍然给我一个段错误。

在文本共享方面我是不是遗漏了什么或在这里犯了错误?

最佳答案

It gives me a segmentation fault in debug (and clear don't work in release), i tried with simple string and char (even one char) and it still gives me a segmentation fault.

这是因为 std::string 不是 POD(普通旧数据)类型。 std::string 在幕后执行动态内存分配(使用 new),并且在序列化它时(例如到共享内存或文件),只有指针被序列化。当反序列化它(从共享内存或文件)到原始指针的内存可能不再存在,这会导致反序列化的字符串不可用。

您必须编写一个函数,专门将字符串显式序列化到您的共享内存,就像标准运算符 std::ostream 运算符 >>(std::ostream& stream, const std::字符串&)

关于c++ - std::string 的共享内存给出段错误 (linux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32581057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com