Code should kill the terminal before generating a loop because it found the value but it is only killing it after looping

Viewed 186

For this project I'm using Visual Studio Code on Windows 11

In this file example StackOverflowTest.py, if there are 5 values in the list, I want the terminal to be killed:

import os
import signal

def kill_terminal():
    os.kill(os.getppid(), signal.SIGTERM)

def test_kill():
    list_test = [1,2,3,4,5]
    if (len(list_test) == 5):
        kill_terminal()

def main():
    print('Start Process')
    test_kill()

I created a loop to activate the main() function from the previous file, but in theory it was to kill the terminal on the first call that is made, but that doesn't happen, it only kills the terminal in the second looping:

from random import randint
import time
import schedule
import StackOverflowTest
import sys

StackOverflowTest.main()
def trigger():
    StackOverflowTest.main()
schedule.every(1).seconds.do(trigger)

while 1:
    schedule.run_pending()
    for remaining in range(randint(5,10), 0, -1):
        sys.stdout.write('\r')
        sys.stdout.write('Next activation in {:2d} seconds'.format(remaining))
        sys.stdout.flush()
        time.sleep(1)
    sys.stdout.write('\r                               \n')

The correct way it should happen would be like this:
As it finds the value 5, the correct thing was to kill the terminal after the first Start Process.

Start Process
~~~~KILL TERMINAL~~~~

However as it is not working correctly, it is happening like this:

Start Process
Next activation in 3 seconds
Next activation in 2 seconds
Next activation in 1 seconds
Start Process
~~~~KILL TERMINAL~~~~

As can be seen he kill the terminal only in the second time run main().

How should I go about solving this problem?

1 Answers

In Windows, signal has a CTRL_C_EVENT that can be sent to console processes that share a common console window. See the documentation here.

So if you replace the kill_terminal function for the following:

def kill_terminal():
    os.kill(os.getppid(), signal.CTRL_C_EVENT)

the terminal closes immediately.

I think the reason why SIGTERM doesn't work is that the Python interpreter process is a child of the cmd.exe process and therefore waits for it. SIGKILL is only available for Unix, so it seems that CTRL_C_EVENT does the job for Windows.

The implementation of signals for Windows is a bit confusing. Read more in this answer.

Possible explanation

Related