0

The accepted answer to this question elaborates how the signal for a process exit can be determined on windows. But if we launch python in the command line using python And try to kill it using task manager or task kill like so:

taskkill /FI "IMAGENAME eq python.exe" ERROR: The process with PID 5616 could not be terminated. Reason: This process can only be terminated forcefully (with /F option).

Using the /F option always sets the %errorlevel% to 1. Is there a way to terminate the python process on windows where the process return code retains the signal information.

EDIT 1: The comments and possible solution possible duplicates of this answer.

Luv
  • 386
  • 4
  • 15
  • 1
    taskkill sends a `WM_CLOSE` message to the top-level and message-only windows. But this instance of python.exe has no windows, so it tells you that it will have to terminate via `TerminateProcess` (i.e. forcefully) with an exit status of 1. – Eryk Sun May 21 '20 at 10:28
  • 1
    If python.exe is started with a new console, e.g. via `start python.exe`, it will be seen by the API as the effective owner of the console window, in which case taskkill will send `WM_CLOSE` to the console, which will in turn send `CTRL_CLOSE_EVENT` to Python's registered console control handlers. If the python.exe process doesn't handle this event by exiting on its own within 5 seconds, the system will terminate the process with the status code `STATUS_CONTROL_C_EXIT` (0xC000013A or -1073741510). – Eryk Sun May 21 '20 at 10:30
  • Thanks That narrows down the search, I will start a different question for a complete solution. – Luv May 21 '20 at 11:30
  • Is this python.exe process running a script that you wrote? If so you can create a message-only window (not visible) owned by a dedicated thread in order to get the normal close message from taskkill. Otherwise, run Python from the command prompt via `start "" /w python.exe " – Eryk Sun May 21 '20 at 11:49
  • In my python program I use popen to launch a second python process, wait on the result but want to know whether it exited because it was killed. – Luv May 21 '20 at 11:58
  • With `subprocess.Popen` you can pass `creationflags=subprocess.CREATE_NEW_CONSOLE` to ensure a child console process allocates a new console. It will thus own the console and be killable via taskkill without /f. However, if it handles `CTRL_CLOSE_EVENT`, it may exit cleanly with an exit status of 0. Also, if the process is forcefully terminated, you will not have anyway to know. System utilities usually terminate a process with an exit status of 1, which is just a generic status code meaning an unsuccessful exit. – Eryk Sun May 21 '20 at 12:01

0 Answers0