HOWTO: Implement a "Kill" Operation in Windows NT

Last reviewed: July 3, 1997
Article ID: Q90749
The information in this article applies to:
  • Microsoft Win32 Application Programming Interface (API) included with: - Microsoft Windows NT version 3.1

SUMMARY

The following sample demonstrates how to implement a "kill" operation, such as a UNIX ps/kill, under Windows NT. Note that PView gives you the PID you need.

The code sample makes use of the Win32 API TerminateProcess(). While TerminateProcess() does clean up the objects owned by the process, it does not notify any DLLs hooked to the process. Therefore, this can easily leave the DLL in an unstable state.

In general, the Task List is a much cleaner method of killing processes.

MORE INFORMATION

The following sample shows how to "kill" a process, given its process ID (PID).

Sample Code

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

   void ErrorOut(char errstring[30])
   /*
   Purpose: Print out an meaningful error code by means of
            GetLastError and printf.

   Inputs:  errstring - the action that failed, passed by the
                        calling proc.

   Returns: none

   Calls:   GetLastError
   */

   {
      DWORD Error;

      Error= GetLastError();
      printf("Error on %s = %d\n", errstring, Error);
   }


   void main(int argc, char *argv[])
   {
      HANDLE hProcess;
      DWORD ProcId;
      BOOL TermSucc;

      if (argc == 2)
      {
         ProcId = atoi(argv[1]);
         hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, ProcId);
         if (hProcess == NULL)
            ErrorOut("OpenProcess");
         TermSucc= TerminateProcess(hProcess, 0);
         if (TermSucc == FALSE)
            ErrorOut("TerminateProcess");
         else
            printf("Process# %.0lx terminated successfully!\n", ProcId);
      }
      else
      {
         printf("\nKills an active Process\n");
         printf("Usage: killproc ProcessID\n");
      }
   }
 

	
	


Keywords : BseProcThrd kbhowto
Version : 3.1
Platform : NT WINDOWS


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: July 3, 1997
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.