C++ Boost Interprocess

Da Andreabont's Wiki.

Le Boost Interprocess sono delle librerie dedicate alla condivisione della ram tra più processi.

Compilare

g++ -std=c++11 -lboost_system -pthread -lrt <file_cpp>

Codice

Scrivere nella memoria condivisa

#include <iostream>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <cstdlib>

#define MEMORYNAME "MySharedMemory"
#define STRINGNAME "MyString"

int main()
{
    
    struct shm_remove
    {
        shm_remove() { boost::interprocess::shared_memory_object::remove(MEMORYNAME); std::cout << "Pulisco...\n";}
        ~shm_remove(){ boost::interprocess::shared_memory_object::remove(MEMORYNAME); std::cout << "Pulisco...\n";}
    } remover;
    
    boost::interprocess::managed_shared_memory segment(boost::interprocess::create_only, MEMORYNAME, 65536);

    auto instance = segment.construct<int> (STRINGNAME) (3);
    
    std::cout << "Value: " << *instance << std::endl;

    return 0;
    
}

Leggere dalla memoria condivisa

#include <iostream>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <cstdlib>
#include <string>

#define MEMORYNAME "MySharedMemory"
#define STRINGNAME "MyString"

int main()
{

    boost::interprocess::managed_shared_memory segment(boost::interprocess::open_only, MEMORYNAME);
    
    auto res = segment.find<int> (STRINGNAME);

    std::cout << "Value: " << *res.first << std::endl;

    return 0;
    
}