1

I want to be able to check the owner of a process of which I got the ID from using C on a Unix system. It also needs to work on cygwin. Additionally it would be nice to get the date the process was created, too.

I've seen there are ways through looking up the generated files in /proc/<process-id>/. But unfortunately on cygwin you would need the right permissions to read those files. If possible I am searching for a way without using those files or system commands. I had also found this threat: How to programatically get uid from pid in osx using c++? But it won't work due to missing definitions of KERN_PROC, KERN_PROC_PID and some more. (Have not found the librarys for those in C)

So in short: Does anyone know how I could get the informations on a specific process using c without needing system calls or reading the files in /proc/?

Banone
  • 11
  • 2
  • look at the source code of `top` in the `procps-ng` package https://gitlab.com/procps-ng/procps – matzeri Aug 05 '22 at 10:18

1 Answers1

0

here under a simple implementation using ps command.

It's certainly not the most elegant but it should work for Unix and Cygwin:

#include <stdio.h>
#include <string.h>
    
int get_proc_uid(int pid, char *uid, int uid_size)
{
 FILE *fp;
 int pid_l, ret = -1;
 char uid_l[16];
 char cmd[64], line[128];
 
 snprintf(cmd, sizeof(cmd), "ps | grep %d", pid);
 fp = popen(cmd, "r");
 if(fp == NULL)
    return ret;
 
 while(fgets(line, sizeof(line), fp) != NULL)
    {
    if(strstr(line, "grep") == NULL)//filter grep dummy result
        {
        sscanf(line, "%d %s", &pid_l, uid_l);
        if(pid_l == pid)
            {
            strncpy(uid, uid_l, uid_size);
            ret = 0;
            break;
            }
        }
    }
 pclose(fp);
 
 return ret;
}
Fabio_MO
  • 713
  • 1
  • 13
  • 26
  • The OP asks for (if possible) "a way without using [...] system commands." – John Bollinger Aug 02 '22 at 13:43
  • Thanks for this answer. After asking I arrived at a similar solution myself (using ps -ef) but found it to be a bit of a roundabout solution. It helps improving my code though. I am still wondering if there is a more 'elegant' way. (My Upvote doesn't count yet as I am a new user) – Banone Aug 03 '22 at 08:17