code_scanner/common/ipc_wrapper.h

74 lines
2.8 KiB
C++

#pragma once
// IPC utility
//
// created on 2022-12-02
//
#include "event_monitor.h"
typedef struct _pack_base
{
uint64_t total_bytes; // total bytes of payload
uint64_t offset; // offset in total of this part
uint64_t bytes; // bytes in data, not include this head
int32_t cmd; // command
char data[0]; // payload
}PACK_BASE, *LPPACK_BASE;
class ipc_wrapper : public parent_holder
{
protected:
event_handler* handler_;
public:
ipc_wrapper(event_handler* handler);
enum ipc_type
{
IPC_FILE = 0, // param: path file
IPC_PIPE, // param: pipe name
IPC_NET, // param: dot-ip:port
IPC_SHARED_MEM, // param: path-file:id:size[:write-ratio-> percent of size of sent buffer, default is 50, only valid in owner]
IPC_USB, // param: vid:pid
IPC_COM, // param: COM1
};
static ipc_wrapper* create_ipc(event_handler* handler, ipc_type type, const char* param);
protected:
virtual ~ipc_wrapper();
public:
// Function: write content to peer
//
// Parameters: pack - content pack
//
// bytes - [in] bytes of data in 'pack', [out] - bytes of data has sent
//
// kbuf - whether memory 'pack' is from IPC, i.e. return from method get_kbuf()
//
// timeout - time out, in milliseconds
//
// Return: 0 - success
// ENOTCONN - the commuction is not connected, equal to !is_ok()
// EDEADLOCK - calling from current thread is disallowed
// ETIME - time out
// ECANCELED - user cancelled the operation
virtual int32_t write(const char* pack, size_t *bytes, bool kbuf, unsigned timeout = WAIT_INFINITE) = 0; // DON'T call in event_handler::on_event routine, it will be DEAD-LOCK !!!
virtual bool is_ok(void) = 0; // whether the commuction is ready
virtual bool is_first(void) = 0; // whether the communication established by me
// Function: obtain IPC internal buffer to reduce ONE memory copy for sent data
//
// Parameter: bytes - [in] desired size; [out] - real size
//
// Return: memory pointer if success, or nullptr. call release_kbuf(ptr) if no longer used
virtual void* get_kbuf(size_t* bytes);
virtual void release_kbuf(void* buf); // release the internal buffer returned by get_kbuf
virtual void clear_kernel_objects(void); // clear all kernel objects the IPC used, used to clear exception
virtual bool cancel_write(void); // cancel current write operation
virtual int32_t stop(void) override; // close the connection
};