2

The following is a Python application which spans a few threads, then spawns a new process of itself and exits:

$ cat restart.py
import os
import random
import signal
import sys 
import threading
import time


class Name(object):
    def __init__(self, name):
        self.name = name


class CallThreads(threading.Thread):
    def __init__(self, target, *args):
        self.target = target
        self.args = args
        threading.Thread.__init__(self)

    def run (self):
        self.target(*self.args)


def main(args):
    print("Hello, world!")
    letter = random.choice(['A', 'B', 'C', 'D', 'E', 'F'])
    count = 0 
    while count<3:
        count += 1
        name = Name(letter+str(count))
        t = CallThreads(provider_query, name)
        t.daemon = True
        t.start()
        time.sleep(3)
        print("------------")

    print("Time to die!")
    t = CallThreads(restart)
    t.daemon = True
    t.start()
    time.sleep(0.1)
    sys.exit(0)


def provider_query(name):
    while name.name!='':
        print(name.name)
        time.sleep(1)


def restart():
    os.system('python restart.py')


def signal_handler(signal, frame):
    sys.exit()


if __name__ == '__main__':
    signal.signal(signal.SIGINT, signal_handler)
    main(sys.argv)

When I hit ^C I do get a bash prompt, but the output still comes and I still see the script in the process table:

$ ps aux | grep restart.py
1000      5751  0.0  0.0   4396   616 pts/3    S    08:41   0:00 sh -c python restart.py
1000      5752  0.3  0.1 253184  5724 pts/3    Sl   08:41   0:00 python restart.py
1000      5786  0.0  0.0   9388   936 pts/4    S+   08:41   0:00 grep --color=auto restart.py

I've tried killing it with kill 5751 && kill 5752, but that doesn't help even if I'm fast enough to do so before the PID changes (on a new process when the script restarts). I've tried pkill restart.py but that does not help either. I'm wary of using pkill python as there are other Python processes running that I don't want to kill. Even closing the Konsole window in which the script is running does not help!

How can I kill the script?

3

I managed to kill it using

pkill -f restart.py

From the man page:

   -f     The pattern is normally only matched against the process name.
          When -f is set, the full command line is used.
0

I could only kill it by running these two commands quickly one after the other a few times (with two taps on the up arrow key):

$ kill -9 `ps aux | grep "sh -c python restart.py" | grep -v grep | awk '{print $2}'`
$ kill -9 `ps aux | grep "0 python restart.py" | grep -v grep | awk '{print $2}'`

What a pain!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.