gpt4 book ai didi

rust - 如何通过 libc::getgroups 为用户获取组?

转载 作者:行者123 更新时间:2023-11-29 08:23:29 25 4
gpt4 key购买 nike

extern crate libc;

fn example(guid: u32) {
unsafe {
let ruid = libc::getuid();
libc::seteuid(guid);
let mut v = vec![0; 0];
let num_groups = libc::getgroups(0, v.as_mut_ptr());
let mut groups = Vec::with_capacity(num_groups as usize);
libc::getgroups(num_groups, groups.as_mut_ptr());
println!(
"real user id {} as user id {}, as user groups {:?}, numgroups {}",
&ruid, &guid, &groups, &num_groups
);
}
}

这打印

real user id 1000 as user id 1000, as user groups [], numgroups 9

我的假设是它会显示一个包含 9 组的向量。

最佳答案

您需要通过添加虚拟元素来更改 groups 的大小,而不仅仅是它的容量。像这样:

unsafe {
let ruid = libc::getuid();
let guid = libc::getgid();
let num_groups = libc::getgroups(0, ::std::ptr::null_mut());
let mut groups = vec![0; num_groups as usize];
libc::getgroups(num_groups, groups.as_mut_ptr());
println!(
"real user id {} as user id {}, as user groups {:?}, numgroups {}",
&ruid, &guid, &groups, &num_groups
);
}

关于rust - 如何通过 libc::getgroups 为用户获取组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50882178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com