How to programmatically retrieve the GID of a running process

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…

Asked By: BobDoolittle

||

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.

Answered By: Celada

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!

Answered By: BobDoolittle
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.