Reputation: 23
I want to run some shell commands in zig which asks for input. For example look at my code, I want to update packages, but that requires sudo password which I obviously cant enter. Im also ok, to just run .sh file with zig, but I want to see progress and obviously be able to input password or smth else if needed. Is there some better way to do this?
const std = @import("std");
pub fn test() !void {
const result = try std.process.Child.run(.{
.allocator = std.heap.page_allocator,
.argv = &[_][]const u8{ "sudo", "xbps-install", "-Su" },
});
}
Upvotes: 0
Views: 884
Reputation: 15673
process.Child
has a stdin_behavior
field that controls how the stdin of the spawned process behaves. This is of type StdIo and by default has the value .Inherit
(meaning that the spawned process will use the same input as your zig program), which will in fact ask for input just fine if you run the process from a terminal. In the .run
function specifically it's set to .Ignore
(which means the spawned process doesn't get any input) so you're not getting any input; But this is just a helper to simplify the most common cases. So to make it work for your case you'll have to invoke the functions from process.Child
"manually".
const cmd = std.process.Child.init(&[_][]const u8{ "sudo", "xbps-install", "-Su" },std.heap.page_allocator);
try cmd.spawn();
// in a real application you'd not want to ignore the status here probably
_ = try cmd.wait();
You can check the source code of process.Child.run
if you need some more inspiration on what you can do here.
Note however that while there are some cases (like complex GUIs which only occasionally require additional privileges) where you may want some mix between root/non-root parts (and there are many ways to accomplish this), but that's not really a typical situation. So for the specific case you're asking about (the sudo
password) my recommendation would actually be to simply not use sudo
and require users to run your original program with root privileges to begin with.
Upvotes: 0