How to get process info programmatically in C/C++

2019-04-13 00:56发布

问题:

Is there a C/C++ library, and documentation about how to collect system and process information on Solaris?

Although I could parse command-line tools, I'd rather use a library that makes the task easier to do.

Thanks

Edit: It has been suggested to use the /proc virtual directory to collect information, however its not much better than parsing command-line tools, in the sense that I'll need to implement some sort of custom parsing for every piece of data I need.

I'm looking for something along the lines of c libraries for Windows or MacOS that provides this information through a c-based systems API, however I'm having no luck with Google.

回答1:

You can get this kind of information with kstat API.

man -s 3KSTAT  kstat

You can see how it is used in OpenSolaris vmstat and iostat source.

For information about processus, I'd look at ps.



回答2:

Solaris has the /proc virtual directory, which allows you to gather all sorts of information about processes using filesystem I/O functions.



回答3:

I would use the /proc virutal dir as CrashWorks has suggested. I've done this on both aux and linux. One thing to keep in mind is when I did use the /proc dir on linux the format of the files varied from one kernel to another.

I don't know what the situation is like on the Solaris side but this could mean that your solution will not be portable from one solaris platform to another.



回答4:

what about getrusage()?



回答5:

I'm definately not an expert on the subject, but I did something very similar for an assignment last semester when we were required to take snapshots of processes. Unfortunately this method requires digging into the kernel which is probably not what you want to do.

I found this article helpful.

Anyways here are some snippets.

 write_lock_irq(&tasklist_lock);
  for_each_process(task) {

    if (system_or_user == 0)
      print_mem_user(task);
    if (system_or_user == 1)
      print_mem_system(task);
  }
  write_unlock_irq(&tasklist_lock);

The idea you need to lock down some data structures or sometimes the kernel will hang. "for_each_process" is a macro defined somewhere but I don't remember how it works D:

static void print_mem_system(struct task_struct *task)
{
  struct mm_struct *mm;

  if (task -> mm == NULL){ // this is how you distinguish system processes from user processes
    myarraypid[totalnumberofprocesses] = task -> pid; // store process id's into myarraypid[], which you can later copy back to user space for printing/display. Additional information would be found in a "task_struct" which is Linux's implementation of a process. 



  }


}

Some of my classmates took different approaches and dived into the source of the "ps" utility. I believe I was working on Linux 2.6.18-92.1.13.e15. Disclaimer: This worked for me but your mileage may vary. I could very well be off the wall and I don't want to lead you down the wrong direction.