返回题库

管道 IPC 订单传输

Pipe Ipc Orders

专题
Systems & Architecture / 系统与架构
难度
L2
来源
MyntBit

题目详情

管道 IPC 是低延迟交易架构中策略引擎与执行网关之间传输订单的关键机制。管道作为连续字节流而非离散消息运行,要求应用层消息边界标记和序列化。

任务:实现 PipeOrderChannel 类,通过 POSIX 管道传输序列化订单。发送端将订单序列化为字节流并写入管道,接收端读取并反序列化。支持消息边界检测和部分读处理。

英文原题

Inter-Process Communication (IPC) via pipes is a critical mechanism in low-latency trading architectures for transmitting orders between strategy engines and execution gateways. Because pipes function as continuous byte streams rather than discrete message queues, receiving systems must implement robust buffering logic to handle data fragmentation and coalescing during binary deserialization.
Task
Implement the OrderStream class to manage a persistent buffer and deserialize incoming byte chunks

解析

问题分析

Unix 管道提供单向字节流 IPC。在父子进程交易架构中,父进程(风控引擎)通过管道向子进程(订单网关)发送经过审批的订单。

实现

struct Order { uint64_t id; char symbol[16]; int qty; double price; };
class OrderPipe {
    int read_fd_, write_fd_;
public:
    OrderPipe() { int fds[2]; ::pipe(fds); read_fd_ = fds[0]; write_fd_ = fds[1]; }
    bool send(const Order& o) { return ::write(write_fd_, &o, sizeof(o)) == sizeof(o); }
    std::optional<Order> recv() {
        Order o;
        if (::read(read_fd_, &o, sizeof(o)) == sizeof(o)) return o;
        return std::nullopt;
    }
    // 子进程关闭 read_fd_, 父进程关闭 write_fd_
};

复杂度与边界

  • 时间复杂度:send/recv O(1) 系统调用
  • 空间复杂度:O(1)(内核缓冲区)
  • 边界条件:(1) 缓冲区满时 write 阻塞(默认 64KB)(2) 写端关闭后 read 返回 0 (3) 仅适合父子进程

英文解析

Analysis

Unix pipes provide unidirectional byte-stream IPC. In parent-child process trading architectures, the parent process (risk engine) sends approved orders to the child process (order gateway) via a pipe.

Solution

struct Order { uint64_t id; char symbol[16]; int qty; double price; };
class OrderPipe {
    int read_fd_, write_fd_;
public:
    OrderPipe() { int fds[2]; ::pipe(fds); read_fd_ = fds[0]; write_fd_ = fds[1]; }
    bool send(const Order& o) { return ::write(write_fd_, &o, sizeof(o)) == sizeof(o); }
    std::optional<Order> recv() {
        Order o;
        if (::read(read_fd_, &o, sizeof(o)) == sizeof(o)) return o;
        return std::nullopt;
    }
    // Child closes read_fd_, parent closes write_fd_
};

Complexity & Edge Cases

  • Time complexity: send/recv O(1) system call
  • Space complexity: O(1) (kernel buffer)
  • Edge cases: (1) write blocks when buffer full (default 64KB) (2) read returns 0 after write end closed (3) Only suitable for parent-child processes

Verification

Send orders between parent/child processes, verify no data loss. Test buffer-full blocking behavior. Confirm clean EOF detection on pipe close.

Key Considerations

Pipe-based IPC separates risk validation from order execution into different processes. If the strategy process crashes, the order gateway (child) continues running. The 64KB default buffer provides natural backpressure - when the gateway cannot process fast enough, the risk engine blocks on send.