Форум сайта python.su
Привет всем!!!
Пытаюсь понять как накодить простенький сервер. Застрял, скрипт не хочет завершаться когда я жму CTRL+C или посылаю kill pid.
Вод код (обрезал все лишнее):
#!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
import signal
import threading
from time import strftime
class TestTread(threading.Thread):
def __init__(self,):
#signal 15 (kill)
signal.signal(signal.SIGTERM, self.mystop)
#signal 2 (ctrl+c)
signal.signal(signal.SIGINT, self.mystop)
threading.Thread.__init__(self)
def run(self):
while(1):
pass
def mystop(self, signum, frame):
write_log("... was stoped")
sys.exit(1)
def write_log(self, tmp_msg):
try:
now_time = strftime("%d.%m.%Y %H:%M:%S")
file = open(log,'a')
file.write(now_time + " - " + tmp_msg+'\n')
file.close()
return 1
except:
return 0
#======================================================
if __name__ == "__main__":
log = "/123.log"
for i in range(1,10):
TestTread().start()
Офлайн
Из докумнтации к модулю signal:
Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution. Any thread can perform an alarm(), getsignal(), pause(), setitimer() or getitimer(); only the main thread can set a new signal handler, and the main thread will be the only one to receive signals (this is enforced by the Python signal module, even if the underlying thread implementation supports sending signals to individual threads). This means that signals can’t be used as a means of inter-thread communication. Use locks instead.
Офлайн
Понял. Спасибо.
Офлайн