Run Linux ps from C++

I am trying to run a Linux ps command from C++.

I can do a system("ps") and it will execute the command, but I need to capture the output and store it in a string.  I tried the obvious set a character array equal to the system("ps") but the string had only a null in it.  Do I need to do a redirect?  If so, I'm not very good with those, how do I do that?

Thanks for the help!
LVL 4
CDirenziAsked:
Who is Participating?
 
woolmilkporcConnect With a Mentor Commented:
Hi,
you could feed the ps command into a 'popen' call.
See below.
This is standard C and not C++, however.
wmp

 #include <stdio.h>
 
main()
{
  FILE *fptr;
  char line[130]; /* line from unix command*/
   
  fptr = popen("ps", "r"); /* Issue the ps command. */
 
/* Read a line */
  while ( fgets( line, sizeof line, fptr))
  {
    printf("%s", line);
 
 /* or process the 'line' as needed */
  }
  pclose(fptr);
}

Open in new window

0
 
Infinity08Commented:
If you want to get the data that ps gives programmatically, I wouldn't use ps to get it - I'd get the data myself from the /proc filesystem.
0
 
CDirenziAuthor Commented:
woolmilk, I'm trying your code now, thanks!

Infinity, how would I go about accessing the user IDs and process IDs?  I need to count the number of users and the number of processes running.

Thanks!
0
 
woolmilkporcCommented:
Hi,
one possibility (besides /proc, as Infinity08 suggests).
is using the utmp file.
Look at the utmp struct found in /usr/include/utmp.h and at the 'getutent()' function.
Here is a small example which counts logged-in users.
wmp
 
 

#include <stdio.h>
#include <utmp.h>
 
main()
{
  struct utmp  *ute;
  int i=0;
 
  while ( ute = getutent() )
  {
   if ( ute->ut_type == USER_PROCESS )
    i++;
  }
 
  printf( "\nNumber of Users is %d\n", i);
 
}

Open in new window

0
 
Infinity08Commented:
The /proc filesystem (procfs) has a directory /proc/<pid> for every running process (where <pid> is the process id).

/proc/<pid>/stat more specifically lists the information used by ps (/proc/<pid>/status is more readable).
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.