Solved

How do you kill a process in "C"

Posted on 2000-04-28
6
871 Views
Last Modified: 2008-02-01
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
Comment
Question by:sdurgala
6 Comments
 
LVL 12

Expert Comment

by:pjknibbs
ID: 2760661
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
 
LVL 12

Expert Comment

by:pjknibbs
ID: 2760666
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
 
LVL 4

Expert Comment

by:captainkirk
ID: 2760679
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
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
LVL 1

Accepted Solution

by:
syscyk earned 100 total points
ID: 2797218
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
 

Author Comment

by:sdurgala
ID: 2801119
It worked GREAT!

Thanks!
0
 
LVL 1

Expert Comment

by:syscyk
ID: 2801484
Thanks, and thanks for the points! Someday, I will get one of those T shirts....
0

Featured Post

The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

789 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question