1

我正在尝试编写一个其中包含 mmap 的函数,但是当我尝试从中访问内存时main(),它会出现段错误。有谁知道为什么?

请忽略 MPI 标头 - 它用于项目的后期部分。我已注释掉该mprotect行以查看它是 mmap 错误,而不是处理程序不一定工作

网络地图.cpp:

#include <iostream>
#include <signal.h>
#include <sys/mman.h>
#include <mpi.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "net_map.h"

using namespace std;

void handler(int sig, siginfo_t* info, void* other)
{
    void* address = info->si_addr;

    cout << "\nSegfault Detected! [Address: " << address << "]\n" << endl;

    int unprotectresult = mprotect(address, SIZE, PROT_READ|PROT_WRITE|PROT_EXEC);

    if (unprotectresult == 0)
    {
        cout << "\nSuccessful mprotect (memory unprotected)!\n" << endl;
    }else 
    {
        cout << "\nMprotect unsuccessful\n" << endl;
    }
}

void netmap (char filename[], char* mapped)
{
    int file;

    file = open(filename, O_RDWR);

    mapped = (char*) mmap(NULL, SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, file, 0);

    if (mapped == MAP_FAILED)
    {
        cout << "\nMap Failed!" << endl;
    }

    cout << mapped << endl;
}

主文件

#include <iostream>
#include <signal.h>
#include <sys/mman.h>
#include <mpi.h>
#include <unistd.h>
#include <array>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <array>
#include "net_map.h"


using namespace std;

int main(int argc, char* argv[])
{

    struct sigaction segaction;

    memset(&segaction, 0, sizeof(segaction));
    segaction.sa_flags = SA_SIGINFO;
    sigemptyset(&segaction.sa_mask);
    segaction.sa_sigaction = handler;
    sigaction(SIGSEGV, &segaction, NULL);

    int i;

    char* mapped;

    networkpage sheet;

    char filename[] = "hello.txt";

    netmap(filename, mapped);

    sheet.address = (void*)mapped;

    cout << "\nAddress: " << sheet.address << endl;

    //mprotect(sheet.address, SIZE, PROT_NONE);

    memcpy(sheet.address, "k", 1);

    munmap(sheet.address, SIZE);

    return 0;
}
4

0 回答 0