/*! \file pisharedmemory.h * \ingroup IO * \~\brief * \~english Shared memory * \~russian Разделяемая память */ /* PIP - Platform Independent Primitives Shared Memory Ivan Pelipenko peri4ko@yandex.ru This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #ifndef PISHAREDMEMORY_H #define PISHAREDMEMORY_H #include "piiodevice.h" //! \~\ingroup IO //! \~\brief //! \~english Shared memory. //! \~russian Разделяемая память. //! \~\details //! \~english //! Shared memory is used as a single data storage accessible to various processes by name. //! At the first opening of the shared memory object, \a size() bytes are allocated, by default 64 KiB. //! All processes must use the same \a size() to avoid errors. //! //! The shared memory object has no read/write position, //! each call to \a read() or \a write() accesses the beginning of memory. //! For working with a specific memory area, overloaded methods with "offset" indication are used. //! //! \~russian //! Разделяемая память используется как единое хранилище данных, //! доступное различным процессам по имени. При первом открытии //! объекта разделяемой памяти выделяется \a size() байт, по умолчанию //! 64 Кб. Все процессы должны использовать один и тот же \a size() //! во избежании ошибок. //! //! У объекта разделяемой памяти нету позиции чтения/записи, //! каждый вызов \a read() или \a write() обращается //! к началу памяти. Для работы с конкретным участком памяти //! используются перегруженные методы с указанием "offset". class PIP_EXPORT PISharedMemory: public PIIODevice { PIIODEVICE(PISharedMemory, "shm"); public: //! \~english Constructs empty %PISharedMemory. //! \~russian Создает пустой %PISharedMemory. //! \~\details //! \~english Constructs an empty shared memory object with default size 64 KiB. //! \~russian Создает пустой объект разделяемой памяти со стандартным размером 64 Кб. explicit PISharedMemory(); //! \~english Constructs a shared memory object with name "shm_name", size "size" and open mode "mode". //! \~russian Создает объект разделяемой памяти с именем "shm_name", размером "size" и режимом открытия "mode". //! \~\details //! \~english Constructs a shared memory object with the specified name, size, and open mode. If "shm_name" is not empty, the object is //! automatically opened. //! \~russian Создает объект разделяемой памяти с заданным именем, размером и режимом открытия. Если "shm_name" не пустой, объект //! автоматически открывается. explicit PISharedMemory(const PIString & shm_name, int size, DeviceMode mode = ReadWrite); //! \~english Destructor. //! \~russian Деструктор. //! \~\details //! \~english Stops and closes the shared memory object. //! \~russian Останавливает и закрывает объект разделяемой памяти. virtual ~PISharedMemory(); //! \~english Reads all shared memory content and returns it as byte array. //! \~russian Читает всю разделяемую память и возвращает её как байтовый массив. //! \~\details //! \~english Reads the entire shared memory and returns it as a PIByteArray. Returns empty array if size is less than or equal to zero. //! \~russian Читает всю разделяемую память и возвращает её как PIByteArray. Возвращает пустой массив, если размер меньше или равен //! нулю. PIByteArray readAll(); //! \~english Returns shared memory size. //! \~russian Возвращает размер разделяемой памяти. //! \~\details //! \~english Returns the size of the shared memory in bytes. Returns -1 if the device is closed. //! \~russian Возвращает размер разделяемой памяти в байтах. Возвращает -1, если устройство закрыто. llong size() const; //! \~english Sets shared memory size. //! \~russian Устанавливает размер разделяемой памяти. //! \~\details //! \~english Sets the size of the shared memory. If the device is open, it will be closed and reopened with the new size. //! \~russian Устанавливает размер разделяемой памяти. Если устройство открыто, оно будет закрыто и открыто заново с новым размером. //! \~\note //! \~english The size is rounded up to the nearest page size on some systems. //! \~russian Размер округляется до ближайшей страницы на некоторых системах. void setSize(llong s); //! \~english Returns if shared memory object is empty (by size). //! \~russian Возвращает пустой ли объект разделяемой памяти (по размеру). //! \~\details //! \~english Returns true if the shared memory size is less than or equal to zero. //! \~russian Возвращает true, если размер разделяемой памяти меньше или равен нулю. bool isEmpty() const { return (size() <= 0); } //! \~english Reads from shared memory to "read_to" no more than "max_size" and returns read bytes count. //! \~russian Читает из разделяемой памяти в "read_to" не более "max_size" и возвращает количество прочитанных байт. //! \~\details //! \~english Reads from the beginning of shared memory (offset 0) to the buffer "read_to" no more than "max_size" bytes. //! \~russian Читает с начала разделяемой памяти (смещение 0) в буфер "read_to" не более "max_size" байт. //! \~\return //! \~english Number of bytes read, or -1 on error. //! \~russian Количество прочитанных байт, или -1 в случае ошибки. //! \~\sa read(void *read_to, int max_size, int offset) int read(void * read_to, int max_size); //! \~english Reads from shared memory starting from "offset" to "read_to" no more than "max_size" and returns read bytes count. //! \~russian Читает из разделяемой памяти с начала "offset" в "read_to" не более "max_size" и возвращает количество прочитанных байт. //! \~\details //! \~english Reads from the shared memory starting at the specified "offset" to the buffer "read_to" no more than "max_size" bytes. //! \~russian Читает из разделяемой памяти с указанного смещения "offset" в буфер "read_to" не более "max_size" байт. //! \~\return //! \~english Number of bytes read, or -1 on error. //! \~russian Количество прочитанных байт, или -1 в случае ошибки. int read(void * read_to, int max_size, int offset); //! \~english Writes to shared memory "data" with size "max_size" and returns written bytes count. //! \~russian Пишет в разделяемую память "data" размером "max_size" и возвращает количество записанных байт. //! \~\details //! \~english Writes to the beginning of shared memory (offset 0) from the buffer "data" no more than "max_size" bytes. //! \~russian Пишет в начало разделяемой памяти (смещение 0) из буфера "data" не более "max_size" байт. //! \~\return //! \~english Number of bytes written, or -1 on error. //! \~russian Количество записанных байт, или -1 в случае ошибки. //! \~\sa write(const void *data, int max_size, int offset) int write(const void * data, int max_size); //! \~english Writes to shared memory starting from "offset" "data" with size "max_size" and returns written bytes count. //! \~russian Пишет в разделяемую память с начала "offset" "data" размером "max_size" и возвращает количество записанных. //! \~\details //! \~english Writes to the shared memory starting at the specified "offset" from the buffer "data" no more than "max_size" bytes. //! \~russian Пишет в разделяемую память с указанного смещения "offset" из буфера "data" не более "max_size" байт. //! \~\return //! \~english Number of bytes written, or -1 on error. //! \~russian Количество записанных байт, или -1 в случае ошибки. int write(const void * data, int max_size, int offset); //! \~english Writes "data" to shared memory. //! \~russian Пишет в разделяемую память "data". //! \~\details //! \~english Writes the entire PIByteArray "data" to the beginning of shared memory (offset 0). //! \~russian Пишет весь PIByteArray "data" в начало разделяемой памяти (смещение 0). //! \~\return //! \~english Number of bytes written, or -1 on error. //! \~russian Количество записанных байт, или -1 в случае ошибки. //! \~\sa write(const void *data, int max_size) int write(const PIByteArray & data) { return write(data.data(), data.size_s()); } //! \~english Writes "data" to shared memory starting from "offset". //! \~russian Пишет в разделяемую память "data" с начала "offset". //! \~\details //! \~english Writes the entire PIByteArray "data" to the shared memory starting at the specified "offset". //! \~russian Пишет весь PIByteArray "data" в разделяемую память с указанного смещения "offset". //! \~\return //! \~english Number of bytes written, or -1 on error. //! \~russian Количество записанных байт, или -1 в случае ошибки. //! \~\sa write(const void *data, int max_size, int offset) int write(const PIByteArray & data, int offset) { return write(data.data(), data.size_s(), offset); } protected: //! \~english Opens the shared memory device. //! \~russian Открывает устройство разделяемой памяти. //! \~\details //! \~english Creates or opens the shared memory object depending on the system (POSIX or Windows). //! \~russian Создает или открывает объект разделяемой памяти в зависимости от системы (POSIX или Windows). //! \~\return //! \~english True on success, false otherwise. //! \~russian True в случае успеха, false в противном случае. bool openDevice() override; //! \~english Closes the shared memory device. //! \~russian Закрывает устройство разделяемой памяти. //! \~\details //! \~english Closes the shared memory object and releases resources. //! \~russian Закрывает объект разделяемой памяти и освобождает ресурсы. //! \~\return //! \~english True on success, false otherwise. //! \~russian True в случае успеха, false в противном случае. bool closeDevice() override; //! \~english Constructs the full path device string. //! \~russian Конструирует строку полного пути устройства. //! \~\details //! \~english Constructs a string in the format "path:size" representing the full path to the shared memory. //! \~russian Конструирует строку формата "path:size", представляющую полный путь к разделяемой памяти. //! \~\return //! \~english The full path device string. //! \~russian Строка полного пути устройства. PIString constructFullPathDevice() const override; //! \~english Configures the device from the full path string. //! \~russian Настраивает устройство из строки полного пути. //! \~\details //! \~english Parses the full path string in the format "path:size" and configures the device. //! \~russian Парсит строку полного пути формата "path:size" и настраивает устройство. //! \~\param full_path //! \~english The full path string to parse. //! \~russian Строка полного пути для парсинга. void configureFromFullPathDevice(const PIString & full_path) override; //! \~english Constructs a variant device representation. //! \~russian Конструирует представление устройства в виде variant. //! \~\details //! \~english Constructs a PIPropertyStorage with "path" and "size" properties representing the device state. //! \~russian Конструирует PIPropertyStorage со свойствами "path" и "size", представляющими состояние устройства. //! \~\return //! \~english The property storage representing the device. //! \~russian Хранилище свойств, представляющее устройство. PIPropertyStorage constructVariantDevice() const override; //! \~english Configures the device from a variant representation. //! \~russian Настраивает устройство из представления variant. //! \~\details //! \~english Configures the device from a PIPropertyStorage containing "path" and "size" properties. //! \~russian Настраивает устройство из PIPropertyStorage, содержащего свойства "path" и "size". //! \~\param d //! \~english The property storage to configure from. //! \~russian Хранилище свойств для настройки. void configureFromVariantDevice(const PIPropertyStorage & d) override; //! \~english Reads from the device. //! \~russian Читает из устройства. //! \~\details //! \~english Calls read() with offset 0. //! \~russian Вызывает read() со смещением 0. //! \~\return //! \~english Number of bytes read. //! \~russian Количество прочитанных байт. ssize_t readDevice(void * read_to, ssize_t max_size) override { return read(read_to, max_size, 0); } //! \~english Writes to the device. //! \~russian Пишет в устройство. //! \~\details //! \~english Calls write() with offset 0. //! \~russian Вызывает write() со смещением 0. //! \~\return //! \~english Number of bytes written. //! \~russian Количество записанных байт. ssize_t writeDevice(const void * data, ssize_t max_size) override { return write(data, max_size, 0); } //! \~english Returns device information flags. //! \~russian Возвращает флаги информации об устройстве. //! \~\details //! \~english Returns the Reliable flag indicating that the device operates reliably. //! \~russian Возвращает флаг Reliable, указывающий, что устройство работает надежно. //! \~\return //! \~english The device information flags. //! \~russian Флаги информации об устройстве. DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Reliable; } private: void initPrivate(); int dsize; PRIVATE_DECLARATION(PIP_EXPORT) }; #endif // PISHAREDMEMORY_H