develooper Front page | perl.perl5.porters | Postings from May 2003

RFC: Alternative approach to kill on Win32 (NT) systems

Thread Next
From:
Daniel Berger
Date:
May 11, 2003 08:08
Subject:
RFC: Alternative approach to kill on Win32 (NT) systems
Message ID:
20030511142047.73710.qmail@web40607.mail.yahoo.com
The current method for killing processes on Win32
systems is to call the TerminateProcess() method
(excluding the PostThreadMessage() used for
pseudo-forks for the moment).  While effective, this
is not the cleanest way to kill a process because it
does not give the process a chance to clean up.

I propose using the CreateRemoteThread() method in
conjunction with the ExitProcess() method, using
TerminateProcess() as a last resort:

/* Some pure C */
int kill(int sig, DWORD pid)
{
   HANDLE hThread;
   DWORD dwThreadId;
   DWORD dwTimeout = 5; /* open for debate */

   HANDLE hProcess =
OpenProcess(PROCESS_ALL_ACCESS,TRUE,pid);

   if(hProcess)
   {
      hThread =
CreateRemoteThread(hProcess,NULL,0,(LPTHREAD_START_ROUTINE)(GetProcAddress(GetModuleHandle("KERNEL32.DLL"),"ExitProcess")),0,0,&dwThreadId);

      if(hThread)
      {
         WaitForSingleObject(hThread,dwTimeout);
         CloseHandle(hThread);
         CloseHandle(hProcess);
         return 0;
      }
      else if(TerminateProcess(hProcess,sig))
      {
         closeHandle(hProcess);
         return 0;
      }
      else
      {
         return -1; /* or whatever for failure */
      }
   }
   else
   {
      return -1; /* process not running */
   }
}

One drawback to this approach is that it's not
supported on Win9x machines.  Another is that this is
still not as clean as calling PostThreadMessage() in
that it can cause unexpected application or system
errors.  However, that scenario probably involves
killing a process you know nothing about or a native
process - neither of which should be done in the first
place.

However, according to msdn.com the ExitProcess()
method is the preferred method for ending a process
because it allows for the process to clean up after
itself, whereas TerminateProcess() may not.

See CreateRemoteThread, ExitProcess, TerminateProcess
and WaitForSingleObject on http://msdn.microsoft.com
for more information.

Regards,

Dan

PS - Hope the formatting is ok - had to do this via
yahoo mail.

__________________________________
Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo.
http://search.yahoo.com

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About