2017-06-27 36 views
0

我有一個在後臺運行幾個python腳本的bash腳本。我附加了一箇中斷信號給他們,這樣當我按ctrl-c時,我可以逃脫所有這些信號。但是,我的python腳本啓動了一個SimpleHTTPServer。該中斷將終止python腳本,但不會終止SimpleHTTPServer。我如何去結束這個過程呢?通過shell中斷kill python服務器

我有以下的外殼在main-script.sh

trap 'kill %1; kill %2' SIGINT 
cd "$DIR_1" && ./script1.py & 
cd "$DIR_2" && ./script2.py & 
./script3.py 

的Python腳本只啓動了一些額外的頭一個SimpleHTTPServer。

運行在終端中的ps x

60958 pts/1 S  0:00 /bin/bash ./main-script.sh 
60959 pts/1 S  0:00 /bin/bash ./main-script.sh 
60960 pts/1 S  0:02 /usr/bin/python ./script1.py host:port1 
60962 pts/1 S  0:01 /usr/bin/python ./script2.py host:port2 

和一個CTRL-C

60960 pts/1 S  0:02 /usr/bin/python ./script1.py host:port1 
60962 pts/1 S  0:01 /usr/bin/python ./script2.py host:port2 

編輯這裏經過的是,啓動服務器的主要代碼:

#!/usr/bin/python 
import SimpleHTTPServer 
import sys 
from SimpleHTTPServer import SimpleHTTPRequestHandler 
import BaseHTTPServer 

def test(HandlerClass=SimpleHTTPRequestHandler, 
     ServerClass=BaseHTTPServer.HTTPServer): 

    protocol = "HTTP/1.0" 

    server_address = (host, port) 
    HandlerClass.protocol_version = protocol 
    httpd = ServerClass(server_address, HandlerClass) 
    httpd.serve_forever() 

if __name__ == '__main__': 
    test() 

任何幫助將不勝感激。謝謝。

+0

包含啓動服務器的代碼,取決於它 –

+1

@ArtemBernatskyi添加了代碼片段。 – JoeFromAccounting

回答

2

其實並不完全確定這是可行的,因爲我在Windows上,現在無法驗證這一點。但是你的python實例應該是接收Ctrl-C信號(或稱爲SIGINT)的實例。

有這一段代碼在Python應該工作:

import signal 
from sys import exit 
from os import remove 

def signal_handler(signal, frame): 
    try: 
     ## == Try to close any sockets etc nicely: 
     ## s in this case is an example of socket(). 
     ## Whatever you got, put the exit stuff here. 
     s.close() 
    except: 
     pass 
    ## == If you have a pid file: 
    remove(pidfile) 
    exit(1) 
signal.signal(signal.SIGINT, signal_handler) 

## == the rest of your code goes here 

這應該抓住SIGINT,並很好地停下來。
如果一切都失敗了,只發生純粹的關機。

+0

奇妙地工作,非常感謝! – JoeFromAccounting

+0

@JoeFromAccounting Joe,來自會計,不客氣。謝謝你提高我的薪水。一切順利//管理員。 – Torxed