• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 890
  • Last Modified:

How do you kill a process in "C"

How do you kill a process in "C"?

I have the Process Id for a process and I want to kill
the process if it's running...

How do I kill the process if I have the Process Id for the process in "C"
on Windows NT?
0
sdurgala
Asked:
sdurgala
1 Solution
 
pjknibbsCommented:
You first need to get a handle to the process using the OpenProcess() function. You'd need:

HANDLE phandle;

phandle = OpenProcess(PROCESS_TERMINATE, FALSE, pid);

where pid is the process ID you've already got. Next, you pass the process handle to TerminateProcess():

TerminateProcess(phandle, 0);

WARNING: Doing this is akin to killing the process through Task Manager--it will not permit the process to clean up any DLLs it uses, and should really only be done to a process which isn't responding to the system. If you're happy with that, fine; otherwise, you should say so and we'll go a bit deeper.
0
 
pjknibbsCommented:
Oh, BTW, you should call CloseHandle() on the process handle after you've finished using it--the process will not be completely flushed from the system until all open handles to it are closed.
0
 
captainkirkCommented:
Here is some code to terminate a list of processes...


#include "stdafx.h"
#include <psapi.h>

void Terminate(char** killMe, const UINT& len)
{
      //char name[MAX_PATH];
      //strcpy(name, killMe);
      //_strlwr(name);
      char** killMe2 = new char* [len];
      for (UINT i = 0; i < len; i++)      {
            killMe2[i] = new char[strlen(killMe[i])+1];
            strcpy(killMe2[i], killMe[i]);
            _strlwr(killMe2[i]);
      }

      DWORD processList[1000], size;
      if (EnumProcesses(processList, sizeof(DWORD)*1000, &size))      {
            for (UINT i = 0; i < size/sizeof(DWORD); i++)      {
                  HANDLE hProcess = OpenProcess(PROCESS_TERMINATE|PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, processList[i]);
                  if (hProcess)      {
                        DWORD cb;
                        HMODULE hModule;
                        if (EnumProcessModules(hProcess, &hModule, sizeof(HMODULE), &cb))      {
                              char base[MAX_PATH];
                              if (GetModuleBaseName(hProcess, hModule, base, MAX_PATH))      {
                                    _strlwr(base);
                                    for (UINT i = 0; i < len; i++)      {
                                          //is it in the list?
                                          if (strcmp(base, killMe2[i]) == 0)
                                                TerminateProcess(hProcess, 0);
                                    }
                              }
                        }
                        CloseHandle(hProcess);
                  }
            }
      }
      for (UINT j = 0; j < len; j++)
            delete [] killMe2[j];
      delete [] killMe2;
}

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
       //Kill all MCAS-VSPM and Synchronizer-related processes.
      //The following are case-insensitive. Add more as needed.

      char* list[] =
      {
            "YourExecutable1.exe",
            "YourExecutable2.exe",
            "YourExecutable3.exe",
      };

      Terminate(list, sizeof(list)/sizeof(char*));
      return 0;
}



This is actually C++ code that you will have to modify to make it "regular C" (change the calls to "new" to malloc() calls, etc) and it makes use of stuff in psapi.lib - if you don't have it, I can send it to you - it's Microsoft stuff...

hope that helps
0
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
syscykCommented:
Hello sdurgala,
  If you HAVE the PID, you can use this code to kill the proc.  Now, this will NOT work on Win 95, but it is just fine for NT. If you want it to work in both NT and Win95, you will have to use a handle to the process instead of the PID.  This is kind of interesting in that it uses the NT security stuff to do its' dirty work.  Tell me what you think.


/*
      kill a proc, great for NT, lousy for Win95
*/
 
BOOL SetPrivilege(
    HANDLE hToken,          // token handle
    LPCTSTR Privilege,      // Privilege to enable/disable
    BOOL bEnablePrivilege   // TRUE to enable.  FALSE to disable
    );
 
void DisplayError(LPTSTR szAPI);

/*
    HERE IS THE ACTUAL CALL! (all rise)
*/

int kill(DWORD pid)
{
    HANDLE hProcess;
    HANDLE hToken;
   
    int dwRetVal=RTN_OK; // assume success from main()
 
    if(!OpenProcessToken(
            GetCurrentProcess(),
            TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
            &hToken
            )) return RTN_ERROR;
 
    // enable SeDebugPrivilege
/*
    if(!SetPrivilege(hToken, SE_DEBUG_NAME, TRUE))
    {
        DisplayError("SetPrivilege");
 
        CloseHandle(hToken);
 
        return RTN_ERROR;
    }
 */
 
   
   // open the process
    if((hProcess = OpenProcess(
            PROCESS_ALL_ACCESS,
            FALSE,
              (DWORD)pid
            )) == NULL)
    {
        DisplayError("OpenProcess");
        return RTN_ERROR;
    }

   
    // disable SeDebugPrivilege
    SetPrivilege(hToken, SE_DEBUG_NAME, FALSE);
 
    if(!TerminateProcess(hProcess, 0xffffffff))
    {
        DisplayError("TerminateProcess");
        dwRetVal=RTN_ERROR;
    }
 
    // close handles
    CloseHandle(hToken);
    CloseHandle(hProcess);
 
    return dwRetVal;
}
 
BOOL SetPrivilege(
    HANDLE hToken,          // token handle
    LPCTSTR Privilege,      // Privilege to enable/disable
    BOOL bEnablePrivilege   // TRUE to enable.  FALSE to disable
    )
{
    TOKEN_PRIVILEGES tp;
    LUID luid;
    TOKEN_PRIVILEGES tpPrevious;
    DWORD cbPrevious=sizeof(TOKEN_PRIVILEGES);
 
    if(!LookupPrivilegeValue( NULL, Privilege, &luid )) return FALSE;
 
    //
    // first pass.  get current privilege setting
    //
    tp.PrivilegeCount           = 1;
    tp.Privileges[0].Luid       = luid;
    tp.Privileges[0].Attributes = 0;
 
    AdjustTokenPrivileges(
            hToken,
            FALSE,
            &tp,
            sizeof(TOKEN_PRIVILEGES),
            &tpPrevious,
            &cbPrevious
            );
 
    if (GetLastError() != ERROR_SUCCESS) return FALSE;
 
    //
    // second pass.  set privilege based on previous setting
    //
    tpPrevious.PrivilegeCount       = 1;
    tpPrevious.Privileges[0].Luid   = luid;
 
    if(bEnablePrivilege) {
        tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED);
    }
    else {
        tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED &
            tpPrevious.Privileges[0].Attributes);
    }
 
    AdjustTokenPrivileges(
            hToken,
            FALSE,
            &tpPrevious,
            cbPrevious,
            NULL,
            NULL
            );
 
    if (GetLastError() != ERROR_SUCCESS) return FALSE;
 
    return TRUE;
}
 
void DisplayError(
    LPTSTR szAPI    // pointer to failed API name
    )
{
    LPTSTR MessageBuffer;
    DWORD dwBufferLength;
    char msg[512];
 
 
    if(dwBufferLength=FormatMessage(
                FORMAT_MESSAGE_ALLOCATE_BUFFER |
                FORMAT_MESSAGE_FROM_SYSTEM,
                NULL,
                GetLastError(),
                GetSystemDefaultLangID(),
                (LPTSTR) &MessageBuffer,
                0,
                NULL
                ))
    {
        DWORD dwBytesWritten;
 
        //
      sprintf(msg,"%s:%s",szAPI,MessageBuffer);
      MessageBox(NULL,msg,"test",MB_OK);
 
        //
        // free the buffer allocated by the system
        //
        LocalFree(MessageBuffer);
    }
}
/*******************/      
0
 
sdurgalaAuthor Commented:
It worked GREAT!

Thanks!
0
 
syscykCommented:
Thanks, and thanks for the points! Someday, I will get one of those T shirts....
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

KuppingerCole Reviews AlgoSec in Executive Report

Leading analyst firm, KuppingerCole reviews AlgoSec's Security Policy Management Solution, and the security challenges faced by companies today in their Executive View report.

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