Best practice for handling Linux window change signal and mutable state

I am hacking on a terminal editor and am trying to update my ui struct’s internal state when the terminal window changes its size. I understand that one can subscribe to a posix channel to get notified when the window changes, like so:

    try posix.sigaction(posix.SIG.WINCH, &posix.Sigaction{
        .handler = .{
            .handler = struct {
                pub fn handler(_: c_int) callconv(.C) void {
                    // TODO: handle update
                }
            }.handler,
        },
        .mask = posix.empty_sigset,
        .flags = 0,
    }, null);

However, when I replace the TODO comment with something like ui.update(), I get a compilation error:

error: mutable 'ui' not accessible from here

This makes sense, but how would you normally go about solving this kind of issue?

I am new to both Zig and systems level programming. Please re-direct me if this is not the correct forum for these kind of questions.

Hello @Zorcal welcome to ziggit :slight_smile:

The inner struct function cannot access outer local variables. It can access global variables.

When handlers are called, the normal execution of your program is interrupted in some unknown state.
Your best strategy is to do almost nothing in the handler; just notify the program about the change e.g. by raising a flag. Then your main program loop can handle the resize.

2 Likes

I see, so basically maintain a global variable of type bool that I set to true on sigwinch, and then set it back to false once the state has been handled? Thanks a lot!

2 Likes

If you are developing with a specific terminal in mind, I’ve written a new spec and a few popular terminals have adopted it. It allows you to subscribe to window size changes in the escape sequence stream instead of needing the global signal handler.

It’s likely not in any released versions, but the development branches of foot, ghostty, kitty, and iterm2 all support it.

4 Likes

That’s great! I like that a lot.

I am daily driving WezTerm, so I would need to support the sigwinch way for a while. But I will definitely keep an eye out for this. I can see you made an issue that I subscribed to.