Cmd Tool – List Processes

This command-line utility can find and list windows processes:

#include <stdio.h>
#include <windows.h>
#include <Tlhelp32.h>

PROCESSENTRY32 proc;

void help() {
   printf(
      "proc - by Jakash3\n"
      "List or find Windows processes.\n"
      "Usage: proc [-p|-n name] [-t]\n\n"
      "Parameters:\n"
      "-t   List process(es) in technical format\n"
      "-p   Finds process matching PID speicifed by name\n"
      "-n   Finds process matching image name specified by name\n\n"
      "Run program without parameters to list all processes\n"
      "Errorlevel set as number of processes found\n"
      "In technical output, the format is as follows:\n"
      "IMAGENAME:PID:THREADS:PARENT PID\n"
   );
}

void showproc(bool tb) {
   if (tb==true) {
      printf(
         "%s:%d:%d:%d\n",
         proc.szExeFile,
         proc.th32ProcessID,
         proc.cntThreads,
         proc.th32ParentProcessID
      );
   } else {
      printf("%s:%d\n",proc.szExeFile,proc.th32ProcessID);
   }
}

int main(int argc, char *argv[]) {
   int count=0;
   if (argc>=2) {
      if ((strcmp(argv[1],"/?")==0)||(strcmp(argv[1],"-?")==0)) {
         help(); return 0;
      }
   }
   proc.dwSize=sizeof(PROCESSENTRY32);
   HANDLE images=CreateToolhelp32Snapshot(TH32CS_SNAPALL,0);
   Process32First(images,&proc);
   while (GetLastError()!=ERROR_NO_MORE_FILES) {
      if (argc>=2) {
         if (strcmp(argv[1],"-p")==0) {
            if (atoi(argv[2])==proc.th32ProcessID) {
               if (argc>=4) {
                  if (strcmp(argv[3],"-t")==0) {
                     showproc(true);
                  }
               } else {
                  showproc(false);
               }
               count++;
            }
         } else if (strcmp(argv[1],"-n")==0) {
            if (strcmp(argv[2],proc.szExeFile)==0) {
               if (argc>=4) {
                  if (strcmp(argv[3],"-t")==0) {
                     showproc(true);
                  }
               } else {
                  showproc(false);
               }
               count++;
            }
         } else if (argc==2 && strcmp(argv[1],"-t")==0) {
            showproc(true);
            count++;
         }
      } else {
         showproc(false);
         count++;
      }
      Process32Next(images,&proc);
   }
   return count;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: