Kill Process Programmatically by PID

By | August 29, 2019

If your computer is slow it could be that some of the running processes is frozen state. So it is time to terminate them. In Windows you can do it thought Task Manager in Mac using Activity Monitor. Similarly the process may be stopped in Windows command prompt by TaskKill command or in Mac/Linux terminal by kill command. Also Windows PowerShell has Linux-like kill command but with different syntax. However sometime it is necessary to terminate process programmatically. Below there are several examples how to do it.
C++ example for Unix like OS::


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
int main(int nn, char ** ss)
{
   if(nn!=3)
   {
      printf(“Arguments required: signal id, process id to kill\n”
         “For example: killtask 6666 9\n”);
      return -1;
   }
   if(strspn(ss[2],”0123456789″)<strlen(ss[2]))
   {
      printf(“Process id should be positive integeri\n”
         “Take process id using \”pidof name_of_process\” command\n”);
      return -1;
   }
   int pid = atoi(ss[2]);
   if(strspn(ss[1],”0123456789″)<strlen(ss[1]))
   {
      printf(“Signal id should be positive integer\n”
         “Take signal id using \”kill -l\” command\n”);
      return -1;
   }
   int signal = atoi(ss[1]);
   int retVal = kill(pid, signal);
   if(retVal == 0)
   {
      printf(“Process with pid=%d has been killed\n”, pid);
   return 0;
   } else {
      switch(errno)
      {
         case EINVAL:
            printf(“An invalid signal=%d was specified\n”, signal);
         break;
         case EPERM:
            printf(“Current process does not have permission to send the signal to process with pid=%d\n”,pid);
         break;
         case ESRCH:
            printf(“Process with pid=%d does not exist\n”, pid);
         break;
         default:
            printf(“Other error with code=%d\n”, errno);
         break;
      }
      return -2;
   }
}

C# example::


using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace killprocess
{
   class Program
   {
      static void Main(string[] args)
      {
         if(args.Length!=1)
         {
            Console.WriteLine(“Argument is required: Process ID to kill”);
            return;
         }
         Regex regex = new Regex(“^[0-9]+$”);
         bool bb = regex.IsMatch(args[0]);
         if (!bb)
         {
            Console.WriteLine(“Process Id should be prositive integer”);
            return;
         }
         int pid = Convert.ToInt32(args[0]);
         try
         {
         nbsp;  Process process2Kill = Process.GetProcessById(pid);
            process2Kill.Kill();
            Console.WriteLine(String.Format(“Process with ID {0} has been terminated”, pid));
         } catch (Exception ex)
         {
            Console.WriteLine(ex.Message);
         ;}
      }
   }
}

C++ example, Win32 API:


#include <stdio.h>
#include <tchar.h>
#include <windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
   if (argc != 2)
   {
      wprintf(L”Argument is required: Process ID to kill\n”);
      return -1;
   }
   if (wcsspn(argv[1], L”01234567890″) < wcslen(argv[1]))
   {
      wprintf(L”Process ID should be positive integer\n”);
      return -1;
   }
   int pid = _wtoi(argv[1]);
   HANDLE handle = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
   if (handle == NULL)
   {
      wprintf(L”Cannot open process with ID %d, error code: %d\n”, pid, GetLastError());
      return -1;
   }
   if (TerminateProcess(handle, -1))
   {
      wprintf(L”Process with ID %d has been terminated\n”, pid, GetLastError());
   }
   else {
      wprintf(L”Termination of the process with ID %d failed, error code: %d\n”, pid, GetLastError());
      return -1;
   }
   CloseHandle(handle);
   return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *