Skip to content

Instantly share code, notes, and snippets.

@SpikedPaladin
Created March 18, 2025 19:42
Show Gist options
  • Save SpikedPaladin/fa10b5a165ad5ac0aa55b5a57c1d9ff0 to your computer and use it in GitHub Desktop.
Save SpikedPaladin/fa10b5a165ad5ac0aa55b5a57c1d9ff0 to your computer and use it in GitHub Desktop.
Vala Custom MainContext
public class Runner : Object {
private Thread<void> thread;
private MainContext ctx;
public Runner() {
ctx = new MainContext();
thread = new Thread<void>("runner", () => {
while (true) {
ctx.iteration(true);
}
});
start_counter.begin();
}
public async void start_counter() {
var count = 0;
var t = Thread<bool>.self<bool>();
message("%p", t);
while (true) {
count++;
if (count == 2) {
run_command("yay libgee"); // Command that will block forever
}
message(@"Current count = $count");
Timeout.add_once(1000, () => start_counter.callback());
yield;
}
}
private void run_command(string command) {
try {
string[] args;
Shell.parse_argv(@"sh -c \"$command\"", out args);
Pid pid;
int stdin, stdout, stderr;
Process.spawn_async_with_pipes(
Environment.get_home_dir(),
args,
Environ.get(),
SpawnFlags.SEARCH_PATH,
null,
out pid,
out stdin,
out stdout,
out stderr
);
message(@"Running command: $command\nPid $pid");
var output = new IOChannel.unix_new(stdout);
var source = output.create_watch(IOCondition.IN | IOCondition.HUP);
source.set_callback((channel, condition) => {
return process_line(channel, condition);
});
// Attach to other thread context
// This will prevent from blocking execution of
// start_counter function
source.attach(ctx);
} catch (Error err) {
message(@"Failed to spawn <$command>: $(err.message)");
}
}
private bool process_line(IOChannel channel, IOCondition condition) {
if (condition == IOCondition.HUP)
return false;
try {
string line;
channel.read_line(out line, null, null); // Thread is blocked here
message(line.strip());
} catch (IOChannelError e) {
return false;
} catch (ConvertError e) {
return false;
}
return true;
}
}
void main() {
var loop = new MainLoop();
new Runner();
loop.run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment