Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 888
  • Last Modified:

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!
0
CDirenzi
Asked:
CDirenzi
  • 2
  • 2
1 Solution
 
woolmilkporcCommented:
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

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now