首页 > 解决方案 > 在 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;
    }
};

标签: c++linuxraspberry-pishared-memory

解决方案


推荐阅读