0

I am new in Linux. I am developing a C application. I need uid of several processes. What I am trying to do is parsing /proc/pid/status file to get Uid of processes.

Name:    init
State:    S (sleeping)
Tgid:    1
Pid:    1
PPid:    0
TracerPid:    0
Uid: 0    0     0     0   0

To parse this file I am thinking of using fscanf function.

Here I want to write some generic code, which works for different lengths of process. But I am confused what is really a good way to parse this file. Can any one help me?

Edit: Here is what I have got. But I have created unnecessary array. I just want to skip till Uid. But I don't know how to.

  char temp[8][1024];

  struct FILE * pFile;

  pFile = fopen ("/proc/1/status","w+");


fscanf(pFile,"%[^\n] %[^\n] %[^\n] %[^\n] %[^\n] %[^\n] %s %s",temp[0],temp[1],temp[2],temp[3],temp[4],temp[5],temp[6],temp[7]);

printf(" User id %s \n",temp[7]);

Thanks

1
  • 1
    You'll get better results from Stack Overflow if you first make an effort to solve the problem yourself and, if you run into trouble: posting your code, describing the results and what's wrong with them. Commented Feb 17, 2014 at 0:58

1 Answer 1

2

You can read the file line by line with getline(it's part of c++, and a GNU extensions in C, not standard C) until you find the Uid, then stop:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int 
main(void)
{   
    FILE * fp; 
    char * line = NULL;
    size_t len = 0;
    ssize_t read;

    fp = fopen("/proc/20204/status", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);

    while ((read = getline(&line, &len, fp)) != -1) {
            char *content;
            content = strtok(line, ":");

            printf("content: %s\n", content);
            if(strncmp(content, "Uid", 3) == 0)
            {   
                    printf("get it:\n");
                    //get the User ID
                    printf("%s\n", strtok(NULL, ":"));
                    break;
            }   
       }  

    if (line)
        free(line);
    exit(EXIT_SUCCESS);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.