Tuesday | 05 NOV 2024
[ previous ]
[ next ]

Forking in Zig

Title:
Date: 2023-11-12
Tags:  zig

This is an example of using the fork function in Zig. This is part of my attempt at adding a FORK function to BASIC.

const std = @import("std");

pub fn main() !void {
    const pid = try std.os.fork();
    if (pid == 0) {
        std.time.sleep(2_000_000_000);
        std.debug.print("Hello, World! - Child\n", .{});
    } else {
        std.debug.print("Hello, World! - Parent\n", .{});
        const result = std.os.waitpid(-1, 0);
        _ = result;
    }
}

This function will print out the parent message and then 2 seconds later print out the child message.

The key things here are that fork reproduces the entire process and continues from the fork line. The difference betweenthe two processes are that the return values for the child and parent are different. This way you can run different things based on the value.

I can already see how this is going to be helpful in subroutines and in main line programs in BASIC. I wonder if I could get away with not using exec. I don't need to launch binaries. PHANTOM is already a fork and an execl, exposing the exec to BASIC may not do much.

The other thing to note is that forked processes run independently of the parent, this means that they will run even if the parent dies. I probably need some way of waiting for a forked process to finish and then do something. I'll need to think about that one. I may need to expose waitpid() as well.

In the above example, you can remove the waitpid and the program will return immediately and put you back at the shell prompt. 2 seconds later the child message will display. The waitpid will wait until the child process returns and then exit the program.