Skip to content

Instantly share code, notes, and snippets.

@enghqii
Created November 18, 2014 18:16
Show Gist options
  • Save enghqii/b8f7aa768262f002234c to your computer and use it in GitHub Desktop.
Save enghqii/b8f7aa768262f002234c to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
void get_command_line(int pid, char * out)
{
char path[256];
FILE* fp;
sprintf(path, "/proc/%d/cmdline", pid); // build up cmdline path
fp = fopen(path, "r");
if(!fp) return;
fgets(out, 256, fp); // we only need to read just one line
fclose(fp);
}
int get_vmsize(int pid)
{
char path[256];
char line[256];
FILE* fp;
int size;
sprintf(path, "/proc/%d/status", pid);
fp = fopen(path, "r");
if(!fp) return;
while(fgets(line, 256, fp) != NULL)
{
if(strstr(line, "VmSize:"))
{
sscanf(line, "VmSize:%d", &size);
break;
}
}
fclose(fp);
return size;
}
int main()
{
DIR* dir; // DIR pointer which points /proc
struct dirent* entry; // DIRectory ENTry
int pid; // process pid
int vmSize = 0;
char cmdLine [256]; // command line
dir = opendir("/proc");
// for each entry of dir
while( (entry = readdir(dir)) != NULL )
{
char path[256];
struct stat fileStat; // has each file info
sprintf(path, "/proc/%s", entry->d_name);
lstat(path, &fileStat); // retriving entry's stat
if(!S_ISDIR(fileStat.st_mode)) // if this entry is not a directory then
{
continue; // we don't need this
}
pid = atoi(entry->d_name); // get pid from filename
if( pid < 0 ) continue; // if pid is not a number then ignore
get_command_line(pid, cmdLine); // retrive cmdline
vmSize = get_vmsize(pid);
//printf("[pid : %d]\t[size : %d]\t[creation time : %d]\t%s\n", pid, vmSize, fileStat.st_ctime, cmdLine);
printf("[%d] \n%s%s%s\n",
pid,
ctime(&fileStat.st_atime), // last access
ctime(&fileStat.st_mtime), // last modif
ctime(&fileStat.st_ctime) // last creation
);
}
closedir(dir);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment