libipc/examples/pongd.zig
Philippe Pittoli 76e3144436 Ready for Zig v0.15.2. Details in commit message.
The library jumped to Zig v0.15.2 which implies a new build system.
`build.zig` now compiles libipc as both static and dynamic libraries,
and provides an entry point to use `libipc` as-is for Zig applications.

Some examples have been added to help new users play with the library.

Thanks to these fairly complete examples, two (very small) leaks related
to sentinel values (in arrays containing paths) were fixed.
2025-10-25 16:35:02 +02:00

86 lines
2.5 KiB
Zig

// Example of a `pong` service using the Zig library directly (not the C bindings).
const std = @import("std");
const ipc = @import("ipc");
const hexdump = ipc.hexdump;
const Message = ipc.Message;
const util = ipc.util;
const builtin = @import("builtin");
const native_os = builtin.target.os.tag;
const print = std.debug.print;
const testing = std.testing;
const service_name = "pong";
fn create_service() !void {
var gpa = std.heap.DebugAllocator(.{.safety = true}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var ctx = try ipc.Context.init(allocator);
defer {
std.debug.print("Deinit context.\n", .{});
ctx.deinit(); // There. Can't leak. Isn't Zig wonderful?
}
// SERVER SIDE: creating a service.
_ = try ctx.server_init(service_name);
// Listen to the standard input (to quit the application).
try ctx.add_external(0);
var some_event: ipc.Event = undefined;
ctx.timer = 20000; // 2 seconds
var count: u32 = 0;
var should_continue = true;
while(should_continue) {
some_event = try ctx.wait_event();
switch (some_event.t) {
.EXTERNAL => {
should_continue = false;
},
.TIMER => {
std.debug.print("\rTimer! ({d})", .{count});
count += 1;
},
.CONNECTION => {
std.debug.print("Connection (fd {d}): {d} so far!\n", .{some_event.newfd, ctx.pollfd.items.len - 1});
},
.DISCONNECTION => {
std.debug.print("User {d} disconnected, {d} remainaing.\n"
, .{some_event.origin, ctx.pollfd.items.len - 1});
},
.MESSAGE_RX => {
if (some_event.m) |m| {
std.debug.print("Message received from {d} ({d} bytes)\n", .{m.fd, m.payload.len});
util.print_message ("RECEIVED MESSAGE", m);
try ctx.schedule(m);
}
else {
std.debug.print("Error while receiving new message. Ignoring.\n", .{});
}
},
.MESSAGE_TX => {
std.debug.print("Message sent to {d}.\n", .{some_event.origin});
},
else => {
std.debug.print("Error: unexpected event\n", .{});
std.debug.print("Quitting.\n", .{});
break;
},
}
}
std.debug.print("Goodbye\n", .{});
}
pub fn main() !u8 {
try create_service();
return 0;
}