We help IT Professionals succeed at work.

Run Linux ps from C++

CDirenzi
CDirenzi asked
on
Medium Priority
988 Views
Last Modified: 2012-05-06
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!
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2013
Top Expert 2013
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

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT
Top Expert 2009

Commented:
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.

Author

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!
CERTIFIED EXPERT
Most Valuable Expert 2013
Top Expert 2013

Commented:
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

CERTIFIED EXPERT
Top Expert 2009

Commented:
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).
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.