Monday 13 February 2012

List Processes using libproc

To learn a little more about processes on a Linux system and to try writing some code in C I adapted some code from this blogpost and wrote a super basic version of the ps command.

On Debian based Linux systems first install libproc.
$ sudo apt-get install libproc-dev

The code:
#include <stdio.h>
#include <string.h>
#include <proc/readproc.h>

int main(int argc, char** argv)
{
 // fillarg used for cmdline
 // fillstat used for cmd
 PROCTAB* proc = openproc(PROC_FILLARG | PROC_FILLSTAT);

 proc_t proc_info;

 // zero out the allocated proc_info memory
 memset(&proc_info, 0, sizeof(proc_info));

 while (readproc(proc, &proc_info) != NULL) {
  printf("%-10d %-10d ", proc_info.tid, proc_info.ppid);
  if (proc_info.cmdline != NULL) {
   // print full cmd line if available
   printf("%s\n", *proc_info.cmdline);
  } else {
   // if no cmd line use executable filename 
   printf("[%s]\n", proc_info.cmd);
  }
 }

 closeproc(proc);
}

To compile:
$ gcc -o myps myps.c -lproc

The command output. The first column is process ID, the second is the parent process ID, and the third is the process command (if in square brackets the command isn't available and the filename of the executable is shown).
$ ./myps
1          0          /sbin/init
2          0          [kthreadd]
3          2          [ksoftirqd/0]
6          2          [migration/0]
29         2          [cpuset]
30         2          [khelper]
31         2          [netns]
33         2          [sync_supers]

... manually deleted output here so it's not too long

14531      12456      /usr/lib/chromium-browser/chromium-browser --type=renderer --lang=en-GB --force-fieldtest=CacheListSize/CacheListSize_12/ConnCountImpact/conn_count_6/ConnnectBackupJobs/ConnectBackupJobsEnabled/DnsImpact/default_enabled_prefetch/DnsParallelism/parallel_default/GlobalSdch/global_enable_sdch/IdleSktToImpact/idle_timeout_10/Instant/HiddenControlB/Prefetch/ContentPrefetchPrerender1/PrerenderFromOmniboxHeuristic/ConservativeAlgorithm/ProxyConnectionImpact/proxy_connections_32/SpdyCwnd/cwndDynamic/SpdyImpact/npn_with_spdy/WarmSocketImpact/warmest_socket/ --channel=12451.0x7f10f46cde00.1990687626
14557      2          [kworker/7:1]
14562      2          [kworker/3:0]
14574      12901      ./myps

To add more columns, take a look at the proc_t struct in the header file /usr/include/proc/readproc.h.

No comments:

Post a Comment