rovf has asked for the wisdom of the Perl Monks concerning the following question:

I want to kill a process which was started with Win32::Process::Create. Just to make clear what about I want to achieve, here a few lines of Unix shell scripting, which I am more familiar with:

# This example is bash or similar myprog & bpid=$! .... kill -KILL $bpid
Here is my Perl solution:
Win32::Process::Create($process_obj,....); .... # Kill! Kill! Kill! $process_obj->Kill(9);
My questions:
  1. Is this really a safe solution, or could there be circumstances where my code would fail?
  2. Also, to what extent could "Kill" be blocking? For example, if Kill allowed the process being killed to gracefully shut down, and is waiting until the process is really gone, it might be that the killer process has to wait until this is done.
  3. If the process being killed, has spawn own subprocesses, will they be killed too automatically?

-- 
Ronald Fischer <ynnor@mm.st>

Replies are listed 'Best First'.
Re: Killing a process on Windows (Win32::Process question)
by BrowserUk (Patriarch) on May 13, 2009 at 15:08 UTC

    The remarks from the underlying system call say

    The TerminateProcess function is used to unconditionally cause a process to exit. The state of global data maintained by dynamic-link libraries (DLLs) may be compromised if TerminateProcess is used rather than ExitProcess.

    TerminateProcess initiates termination and returns immediately. This stops execution of all threads within the process and requests cancellation of all pending I/O. The terminated process cannot exit until all pending I/O has been completed or canceled.

    A process cannot prevent itself from being terminated.

    1. Killing a process (on any OS) is never 'safe'--for the process being killed--in that it may cause data loss.

      If you are creating the process you are killing, and have taken no extraordinary measures to raise its priviledges, or drop your own, there should be no circumstances in which the kill attempt will fail.

    2. Kill returns immediately to the caller. It may take a short while for the killed process to go away due to pending IO.
    3. Generally no.

      However, on later versions of the OS, it is possible for processes to be added to a Job Object with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE which can cause other processes that are part of the same job object to be terminated automatically. But the creating process has to cooperate for that to happen.

    One point to note. You are passing '9' to the kill call--presumably based upon the *nix kill 9, pid meme. The value passed to the Kill method does not control how the process is terminated. Ie. it is not a signal value. It is simply the exit code that is returned to anyone calling GetExitCode() for the process you've killed. As such, you should chose a value that makes sense in the environment you are running.

    For example 9, translates to The storage control block address is invalid. which doesn't make a lot of sense in this circumstance.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      Thanks a lot for the elaborate and extremely helpful answer!

      For example 9, translates to The storage control block address is invalid.

      I didn't know that there are exit codes with predefined meaning. Do you happen to know where I find a list of these codes? In my case, the reason would be "Killing because of Timeout" (the process runs for too long time).

      -- 
      Ronald Fischer <ynnor@mm.st>

        16000 and counting.

        You can look through to find something very specific for your purposes--which would be a damn sight easier if they would put them all on one searchable page.

        A couple that might be suitable that I already encountered before are:

        ERROR_CONTROL_C_EXIT 572 (0x23C) ERROR_FATAL_APP_EXIT 713 (0x2C9)

        Generic enough that they aren't likely to be confused with any "expected values"--specific enough to suggest something abnormal happened.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
        winerror.h
        The closest I can find is ERROR_TIMEOUT which has a value of 1460. Unfortunately the Windows implementation of Perl does not allow return codes > 255 from a process (because of Perl's UNIX history).
Re: Killing a process on Windows (Win32::Process question)
by John M. Dlugosz (Monsignor) on May 13, 2009 at 15:51 UTC
    I've mused on this in the past, and decided on a hierarchy of kills. How do you tell the program to shut down gracefully? If it's a GUI program, posting the proper message to the main window, or perhaps broadcasting it to be save, is my first step.

    Another thing, which is not built in to the OS but is useful on modern programs that use exception handling, is to break in and make all the threads throw exceptions. This will (might) unwind the stack and call destructors, and may close files and stuff more gracefully than just stopping. Or having it call ExitProcess from that process will at least tell the DLLs to clean up.

    My experience in Windows is that sometimes a stuck process will not go away, even when attempted to kill from Sysinternals' Process Explorer. This is probably due to it having pending I/O or otherwise stuck in some system thread. The system shutdown procedure apparently has some stronger way to deal with them, after a long time out.

    The MSDN, on Terminating a Process, suggests making a custom window message that is known to both processes, and avoid calling TerminateProcess. More generally, build the program so it can be told to stop in a graceful way.

    As for your last question, Windows doesn't track "sub"processes. Any started process is a peer to all others. Process Explorer goes to some effort to figure it out anyway, and its "kill tree" identifies them all and kills each individually.

    —John

        I know. But just starting a process doesn't automatically associate it with the parent. Process Explorer, which I highly recommend, highlights Jobs in a ochre. They are seldom used. I see trees of processes started by a project build, some programs such as Open Office, the virus checking system, and of course Explorer and the various command shells, and from using git. None of them use Job objects.

        —John

      How do you tell the program to shut down gracefully? If it's a GUI program, posting the proper message to the main window, or perhaps broadcasting it to be save, is my first step.

      The problem is that I don't know anything about the process to be killed. In theory, it could be anything. In practice, it is very often a (non-GUI) C++ application, which has run on a CASSERT, which in turn pops up a message box, and the process waits forever that some kind soul would click the message box away. But this is only the "typical" scenario, not the only one. The reason is that I don't write the applications which run into those processes, so I can't know in advance what they are going to do....

      -- 
      Ronald Fischer <ynnor@mm.st>
        Ah, then you really want to look for popup-killers. There are ways to prevent modal dialog boxes from appearing at all. This is used on services and servers that are sloppy or incorporate parts that were not so-designed.

        You can also be more targeted, noticing that the process has a window of the expected Class to be that popup, and feeding it a message. I think some popup-killers work that way, after the fact. Others prevent them from working in the first place.

        —John

Re: Killing a process on Windows (Win32::Process question)
by cdarke (Prior) on May 13, 2009 at 15:35 UTC
    In addition, you imply that kill might not totally remove a process, and you are correct. On Windows (like UNIX) another process can query the exit code (as BrowserUk mentioned) after the process has died. Therefore there is some residual resource (a couple of pages, I recall) kept while a process handle is open, even though is no longer appears in Task Manager. On UNIX we would call that a zombie, so make sure you close the process handle. Unlike UNIX, that process handle could be held by any other process, not just the parent.

    In addition, also in the MSDN for TerminateProcess: The terminated process cannot exit until all pending I/O has been completed or canceled. This can be an issue with comms IO.

    You also ask about 'subprocesses': Terminating a process does not cause child processes to be terminated.
Re: Killing a process on Windows (Win32::Process question)
by tokpela (Chaplain) on May 14, 2009 at 09:10 UTC

    I think you might want to look at Win32::Job

    This module will allow you to create process which can contain subprocesses. The module contains the ability to timeout after a period of time and then allows you to kill the process (and subprocesses).

    From the documentation:

    Windows 2000 introduced the concept of a "job": a collection of processes which can be controlled as a single unit. For example, you can reliably kill a process and all of its children by launching the process in a job, then telling Windows to kill all processes in the job. Win32::Job makes this feature available to Perl.

    For example, imagine you want to allow 2 minutes for a process to complete. If you have control over the child process, you can probably just run it in the background, then poll every second to see if it has finished.

    That's fine as long as the child process doesn't spawn any child processes. What if it does? If you wrote the child process yourself and made an effort to clean up your child processes before terminating, you don't have to worry. If not, you will leave hanging processes (called "zombie" processes in Unix).

    With Win32::Job, just create a new Job, then use the job to spawn the child process. All its children will also be created in the new Job. When you time out, just call the job's kill() method and the entire process tree will be terminated.

      The problem is that the creation of subprocesses happens outside my Perl application. I basically get as input a string, which contains some Windows command (typically the name of a Batch file). I then need to create a job (I create a console for this), and this is the job which I want to kill when it runs for too long. The problem is that I have no idea what the batch file will be doing. It can call some EXE file which in turn creates tons of subprocesses. If I understand you right, Win32::Job won't help me in this case.

      -- 
      Ronald Fischer <ynnor@mm.st>
        If I understand you right, Win32::Job won't help me in this case.

        Actually, it probably will. According to the docs:

        By default, processes created using CreateProcess by a process associated with a job are associated with the job;

        Which mean if you create a job (a Win32::Job), and then associate the top level process you start with that job, then any processes it spawns will also be associated with that job. You should then be able to kill them all by killing the job.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.