5

I need to write some C code to check the effective GID of a running process whose PID I know. I've not found any direct way to do this. There are a number of heavyweight kludges I could use, such as invoking popen("/bin/ps ARGS", "r") and parsing its output, or fopen("/proc/PID/status", "r") and parsing that output, but I'm looking for a cleaner, more direct approach. If only getegid() took a PID argument...

  • Isn't this what you want? pubs.opengroup.org/onlinepubs/009695399/functions/getpgid.html – slm Jul 2 '14 at 23:17
  • @slm No, getpgid concerns the PGID = process group ID, which is a parameter related to job control and not related to the security credentials UID/EUID/GID/EGID – Celada Jul 3 '14 at 1:54
  • OK - sorry to keep throwing links to you but what about this code: c.happycodings.com/c-on-unix/code12.html – slm Jul 3 '14 at 1:59
  • @slm The OP already mentioned getegid() and that system call is only able to give you your own GID, not that of another process. Too bad about that :-( – Celada Jul 3 '14 at 2:12
2

I don't know of any portable way to do this. I thought maybe ptrace(), but I can't see how from the manpage. Even if that works, "tracing" the other process in any way is probably unnecessarily invasive

For Linux, your suggestion to use fopen("/proc/PID/status", "r") is about as clean and direct as you're going to get. It seems to be what gdb does.

  • It seems crazy to parse multiple lines of a text file to do a simple thing like this, but this is what I was afraid of. Thanks. – BobDoolittle Jul 3 '14 at 13:39
  • 2
    You can also do stat("/proc/nnn", &stb); the process's effective gid will be in stb.st_gid. This is simultaneously more portable (it works on Linux and FreeBSD) and less portable (it's not documented). – Mark Plotnick Jul 6 '14 at 4:41
  • 1
    @MarkPlotnick great idea, I didn't think of that. – Celada Jul 15 '14 at 22:08
  • @MarkPlotnick That is a great idea! Somehow I never saw it when you made this comment. Can you make it an actual answer so I can mark it as such for others? – BobDoolittle Jan 1 '17 at 20:08
0

This appears to be a very popular question, so I want to make the answer very clear. @MarkPlotnick gave the best answer, as a comment to the previous (pretty good) answer, but we haven't gotten his attention to repost it so I can accept it as a proper answer and help people out. So, with apologies to Mark:

Mark Plotnick says: You can also do stat("/proc/nnn", &stb); the process's effective gid will be in stb.st_gid. This is simultaneously more portable (it works on Linux and FreeBSD) and less portable (it's not documented).

Thanks Mark!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.