c++ - 在 C++ 中使用共享内存时出现 SIGSEGV 错误
问题描述
我在 Linux 的树莓派上的两个应用程序之间做一个非常简单的 IPC,一个应用程序发送,另一个应用程序接收
在通宵运行期间,该进程因SIGSEGV
错误而崩溃。
strcpy(str, in_string);
它在发送应用程序中崩溃了
什么会导致这种类型的崩溃?
我写入内存的字符串大小都相同,并且我假设它总是写入相同的内存位置,但我知道 linux 使用虚拟内存,所以物理地址可能会发生变化。
#pragma once
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
class LocalSocket {
public:
LocalSocket()
{ // ftok to generate unique key
key_t key = ftok("shmfile", 65);
// shmget returns an identifier in shmid
shmid = shmget(key, 1024, 0666 | IPC_CREAT);
// shmat to attach to shared memory
str = (char*) shmat(shmid, (void*)0, 0);
}
~LocalSocket()
{
//detach from shared memory
shmdt(str);
// destroy the shared memory
shmctl(shmid, IPC_RMID, NULL);
}
int shmid;
char *str;
bool Send(char* in_string)
{
strcpy(str, in_string);
printf("Data written in memory: %s\n", str);
return true;
}
bool Receive(char* out_string)
{
printf("Data read from memory: %s\n", str);
strcpy(out_string, str);
return true;
}
};
解决方案
推荐阅读
- spring-cloud-stream - OpenTracing、Spring Cloud Stream 和 Solace
- google-apps-script - 设置 Oauth2 以使用电子表格获取访问令牌
- java - Katalon studio - 如何使用不同的循环写入不同的excel列
- r - 如何“取消嵌套”两个不兼容的嵌套 tibble 列?
- php - 如何递归地添加一个数组作为另一个数组的孩子?
- java - Spring Boot AccessDecisionVoter 自定义未授权消息
- installation - 安卓手机上没有安装app
- c - OpenSSL 1.1 通过 IANA ID 获取密码套件
- components - 如何在苗条的故事书中使用“插槽”
- python - 通过浏览按钮选择目录