如何终止启动新进程的脚本?

如何终止启动新进程的脚本?

下面是一个 Python 应用程序,它跨越几个线程,然后生成一个新的进程并退出:

$ 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)

当我点击时,^C我确实收到了 bash 提示符,但输出仍然出现,并且我仍然在进程表中看到脚本:

$ 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

我尝试用 杀死它kill 5751 && kill 5752,但是即使我足够快,可以在 PID 更改之前(在脚本重新启动时在新进程上)执行此操作,这也无济于事。我已经尝试过了pkill restart.py,但这也没有帮助。我对使用持谨慎态度pkill python,因为还有其他我不想杀死的 Python 进程正在运行。即使关闭运行脚本的 Konsole 窗口也无济于事!

我怎样才能杀死脚本?

答案1

我设法用它杀死了它

pkill -f restart.py

从手册页:

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

答案2

我只能通过快速运行这两个命令几次来杀死它(点击向上箭头键两次):

$ 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}'`

多么痛苦啊!

相关内容