Archived
3
0
This repository has been archived on 2024-06-18. You can view files and clone it, but cannot push or open issues or pull requests.
libipc-old/zig-impl/apps/pong.zig

72 lines
2.0 KiB
Zig
Raw Normal View History

2022-12-31 04:59:06 +01:00
const std = @import("std");
const net = std.net;
const fmt = std.fmt;
const os = std.os;
const print = std.debug.print;
const ipc = @import("ipc");
const hexdump = ipc.hexdump;
2023-01-05 11:07:29 +01:00
const Message = ipc.Message;
2022-12-31 04:59:06 +01:00
pub fn main() !u8 {
const config = .{.safety = true};
var gpa = std.heap.GeneralPurposeAllocator(config){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var ctx = try ipc.Context.init(allocator);
defer ctx.deinit(); // There. Can't leak. Isn't Zig wonderful?
2023-01-05 11:07:29 +01:00
// The service to contact, either provided with the SERVICE envvar
// or simply using "pong".
var should_free_service_to_contact: bool = true;
var service_to_contact = std.process.getEnvVarOwned(allocator, "SERVICE") catch blk: {
should_free_service_to_contact = false;
break :blk "pong";
};
defer {
if (should_free_service_to_contact)
allocator.free(service_to_contact);
}
2022-12-31 04:59:06 +01:00
2023-01-05 11:07:29 +01:00
var pongfd = try ctx.connect_ipc(service_to_contact);
var message = try Message.init(pongfd, allocator, "bounce me");
2023-01-05 11:07:29 +01:00
try ctx.schedule(message);
2022-12-31 04:59:06 +01:00
var some_event: ipc.Event = undefined;
2023-01-05 11:07:29 +01:00
ctx.timer = 2000; // 2 seconds
2022-12-31 04:59:06 +01:00
while(true) {
some_event = try ctx.wait_event();
switch (some_event.t) {
.TIMER => {
print("Timer!\n", .{});
},
2023-01-05 11:07:29 +01:00
.MESSAGE_RX => {
2022-12-31 04:59:06 +01:00
if (some_event.m) |m| {
2023-01-05 11:07:29 +01:00
print("message has been bounced: {}\n", .{m});
2022-12-31 04:59:06 +01:00
m.deinit();
2023-01-05 11:07:29 +01:00
break;
2022-12-31 04:59:06 +01:00
}
else {
2023-01-05 11:07:29 +01:00
print("Received empty message, ERROR.\n", .{});
break;
2022-12-31 04:59:06 +01:00
}
},
2023-01-05 11:07:29 +01:00
.MESSAGE_TX => {
2023-01-05 11:07:29 +01:00
print("Message sent.\n", .{});
},
2022-12-31 04:59:06 +01:00
else => {
2023-01-05 11:07:29 +01:00
print("Unexpected event: {}, let's suicide\n", .{some_event});
2022-12-31 04:59:06 +01:00
break;
},
}
}
print("Goodbye\n", .{});
return 0;
}