我想知道有没有办法找出打开的套接字然后关闭它?
例如,我有一个脚本" SendInfo.py"它打开一个套接字并通过TCP发送一些信息。
如果我调用此脚本来运行它,例如" python SendInfo.py" ,它会打开一个新的插座。
如果我使用" python SendInfo.py"再次运行此脚本,它将发送一些更新的信息,我想取消之前的TCP事务并开始一个新事务 - 例如通过关闭前一个套接字。
如何在脚本开头访问打开的套接字才能关闭它?我试过调查线程,但我同样对哪些线程是开放的以及如何关闭开放线程等感到困惑。
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(2)
s.connect((self.__host, PORT))
答案 0 :(得分:1)
我不确定这是否是你所追求的,但这里有一种确保脚本只运行一次并杀死现有运行脚本的方法。
你可能会发现一些有用的东西。 (这适用于Linux)
#!/usr/bin/python
# running.py
# execute by making the script executable
# put it somewhere on $PATH and execute via running.py
# or execute via ./running.py
import os, sys, time , signal, socket
running_pid = os.popen('ps --no-headers -C running.py').read(5)
try:
running_pid = int(running_pid)
except:
running_pid = 0
current_pid = int(os.getpid())
if running_pid != 0:
if running_pid != current_pid:
print "Already running as process", running_pid
print "Killing process", running_pid
os.kill(int(running_pid), signal.SIGKILL)
# sys.exit()
# Create a listening socket for external requests
tcp_port = 5005
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
print "Error on Socket 5005"
# force re-use of the socket if it is in time-out mode after being closed
# other wise we can get bind errors after closing and attempting to start again
# within a minute or so
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.settimeout(0.10)
sock.bind(("localhost", tcp_port))
except IOError as msg:
print "Error on Socket Bind "+str(tcp_port)+", running.py is probably already running"
pass
try:
sock.listen((1))
except:
print "Error on Socket listen"
time.sleep(60)
sock.close()