LibC get current group id

Hi guys, I have one question. Long time ago, I asked if there is a command to get the current user id.

We told me it’s:

LibC.getuid

But what is the way to know if the current user is member of a group id ?

Hi, I’m a Rubyist and I’m totally new to Crystal. I saw your question and it caught my attention, and I would like to share my “solution”.

It seems to somewhat be working, but it doesn’t follow conventions, lacks error checking, and is obviously not production-ready, among other issues.

Happy coding! :nerd_face:

require "system/user"

lib LibC
  # https://man7.org/linux/man-pages/man2/getgroups.2.html
  # int getgroups(int size, gid_t list[_Nullable .size]);
  fun getgroups = getgroups(size : Int, list : GidT*) : Int

  # https://man7.org/linux/man-pages/man3/getgrouplist.3.html
  # int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);
  fun getgrouplist = getgrouplist(user : Char*, group : GidT, groups : Int*, ngroups : Int*) : Int
end

size = LibC.getgroups(0, nil)
puts "size: #{size}"

groups = Pointer(LibC::GidT).malloc(size)
LibC.getgroups(size, groups)
puts groups.to_slice(size)

#
puts "*" * 69
#

user = System::User.find_by(name: "root")

ngroups = Pointer(LibC::Int).malloc(1)
LibC.getgrouplist(user.username, user.group_id.to_i32, nil, ngroups)
puts "ngroups: #{ngroups.value}"

groups = Pointer(LibC::Int).malloc(ngroups.value)
LibC.getgrouplist(user.username, user.group_id.to_i32, groups, ngroups)
puts "groups: #{groups.to_slice(ngroups.value)}"