Processes: How can I kill a process?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

Thread: Processes: How can I kill a process?

Hybrid View

  1. #1
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Processes: How can I kill a process?

    Q: How can I kill a process?

    A: There are different ways depending whether the process will be killed from inside or outside. For killing a process from inside the function 'ExitProcess()' can be used.


    Code:
    ::ExitProcess(0);    // Zero is the exit code in this example
    This will close the actual process. It is the preferred method to end a process and provides a clean shutdown of the process. Note that this function should not be called from inside a DLL since this could lead to unexpected application or system errors.

    To kill a process from outside a 'WM_CLOSE' message should be sent to its primary thread. If the process was created with 'CreateProcess()' the 'PROCESS_INFORMATION' structure contains the ID of the primary thread which in turn can be used with 'PostThreadMessage()'...


    Code:
    ::PostThreadMessage(piProcessInfo.dwThreadId, WM_CLOSE, 0, 0);
    This (unfortunately) will only work if the primary thread of the process has created a message queue otherwise 'PostThreadMessage()' will fail. In this case the only possibility is to force the process to close by a call to 'TerminateProcess()'. Therefore a combination of 'PostThreadMessage()', 'WaitForSingleObject()' and 'TerminateProcess()' should be used as follows:


    Code:
    ::PostThreadMessage(piProcessInfo.dwThreadId, WM_CLOSE, 0, 0);
    ::WaitForSingleObject(piProcessInfo.hProcess, 1000);
          
    // Check exit code
    DWORD dwExitCode = 0;
    ::GetExitCodeProcess(piProcessInfo.hProcess, &dwExitCode);
    if(dwExitCode == STILL_ACTIVE)
    {
      // Process did not terminate -> force it
      ::TerminateProcess(piProcessInfo.hProcess, 0);  // Zero is the exit code
                                                      // in this example
    }
    'TerminateProcess()' has some drawbacks which should be considered. It causes all threads within the process to terminate, and causes the process to exit, but DLLs attached to the process are not notified that the process is terminating. Additionally child processes of the terminating process will not be terminated. Therefore 'TerminateProcess()' should only be used in extreme circumstances.

    There exists a knowledge base article which also covers the topic of a 'clean' termination of a process.


    Last edited by Andreas Masur; July 21st, 2005 at 04:55 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center