Como matar um script que inicia novos processos?

2

O seguinte é um aplicativo Python que abrange alguns segmentos e gera um novo processo e sai:

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

Quando eu clico em ^C , recebo um prompt bash, mas a saída ainda aparece e ainda vejo o script na tabela de processos:

$ 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

Eu tentei matá-lo com kill 5751 && kill 5752 , mas isso não ajuda mesmo se eu for rápido o suficiente para fazer isso antes que o PID mude (em um novo processo quando o script for reiniciado). Eu tentei pkill restart.py , mas isso não ajuda também. Tenho receio de usar pkill python , pois há outros processos em Python em execução que não quero matar. Mesmo fechar a janela do Konsole em que o script está sendo executado não ajuda!

Como posso matar o script?

    
por dotancohen 01.08.2013 / 07:58

2 respostas

3

Consegui matá-lo usando

pkill -f restart.py

Da página do manual:

   -f     The pattern is normally only matched against the process name.
          When -f is set, the full command line is used.
    
por 01.08.2013 / 11:44
0

Eu só poderia matá-lo executando esses dois comandos rapidamente um após o outro algumas vezes (com dois toques na tecla de seta para cima):

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

Que dor!

    
por 01.08.2013 / 12:11