0

I would like to read and print the status of pid of a process in linux using C.

for(p=0; p<=j; ++p)
{
    char buf[512];
    FILE *process = popen("pidof -s process[j]", "r");//process[j] contains the cmd line
    fgets(buf, 512,process);
    pid_t pid = strtoul(buf, NULL, 10);
    printf("%s",buf,512);
    p=pid;
    char status= fscanf("/proc/[pid]/stat", "%s", buf[512]);
} 

i.e. I would like the status of the process to be printed.

I was able to read the pid of the processes. But I failed in reading the status from:

/proc/[pid]/stat

And printing the status of the process.

Saurabh Jadhav
  • 11
  • 1
  • 1
  • 7
  • Aside from needing to use `sprintf` in a few places to insert numbers into strings in the proper place, and giving `fscanf` the correct arguments, you're most of the way there. Look at https://stackoverflow.com/questions/8257714/how-to-convert-an-int-to-string-in-c and come back if you have any questions. – Mark Plotnick Jul 16 '17 at 17:47
  • @MarkPlotnick I was able to get the pids for the cmd lines of processes stored in process[j]. I would like to print status of each process using C – Saurabh Jadhav Jul 16 '17 at 17:52
  • Can you edit the question to show what the output should look like? Programs like `ps` read from the status files but add some formatting to make the info more readable. – Mark Plotnick Jul 16 '17 at 17:53
  • @MarkPlotnick Check the edit, I made the necessary changes. – Saurabh Jadhav Jul 16 '17 at 18:13
  • `fscanf` takes a FILE* as its first argument. You are passing it a path. – William Pursell Jul 16 '17 at 18:59

1 Answers1

0

use: cat/proc/[pid]/stat

instead of: /proc/[pid]/stat

rohn71
  • 1