#ifndef __REPLICA_SHM_H__ #define __REPLICA_SHM_H__ #include #include #ifndef REPLICA_SHM_NAME #define REPLICA_SHM_NAME "/kvs_replica_shm" #endif #ifndef REPLICA_SHM_SIZE // 64MB,按需调 #define REPLICA_SHM_SIZE (256u * 1024u * 1024u) #endif // 每条记录头部(放在 shm 的 data 区里) typedef struct __attribute__((packed)) { uint64_t seq; // 单调递增 uint32_t len; // payload bytes uint32_t flags; // 预留:压缩、类型等 uint32_t crc32; // 可选:0 表示不校验 uint32_t reserved; // 对齐 // uint8_t payload[len] 紧跟其后 } replica_rec_hdr_t; // shm 顶部元数据 typedef struct __attribute__((packed)) { uint32_t magic; uint32_t version; uint64_t capacity; // data 区大小(字节) uint64_t write_off; // producer 写指针(0..capacity-1) uint64_t last_seq; // producer 最新 seq uint8_t _pad[64]; // cacheline padding // 后面紧跟 data[capacity] } replica_shm_hdr_t; typedef struct { int fd; size_t map_size; replica_shm_hdr_t *hdr; uint8_t *data; } replica_shm_t; // kvstore: 初始化(create/open + mmap) int replica_shm_open(replica_shm_t *s, const char *name, size_t total_size, int create); // kvstore: append 一条记录,返回 off(相对 data 起始),用于 notify // 单写者设计:无需锁。返回 0 成功,<0 失败(空间不足或参数错误) int replica_shm_append(replica_shm_t *s, uint64_t seq, const void *buf, uint32_t len, uint32_t *out_off); // replicator: 读取记录头(不移动游标),你也可以直接 memcpy payload // off 是 data 内偏移 int replica_shm_peek(replica_shm_t *s, uint32_t off, replica_rec_hdr_t *out_hdr); // 关闭 void replica_shm_close(replica_shm_t *s); extern replica_shm_t g_rep_shm; #endif