我有一个用 Python 编写的线程服务器,我开始使用以下 shell 脚本:
#!/bin/bash
base_path="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
public_dns=$(curl -s http://169.254.169.254/latest/meta-data/public-hostname)
echo $public_dns > "$base_path/client/address"
cd "$base_path/server"
python "server.py" &
echo $! > "$base_path/server_pid"
echo "Server running"
我将 PID 回显到一个文件,以便我可以使用另一个 shell 脚本关闭服务器:
#!/bin/bash
base_path="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
kill -9 `cat "$base_path/server_pid"`
rm "$base_path/server_pid"
rm "$base_path/client/address"
但是,我知道,考虑到服务器有许多线程将 I/O 输入到网络和硬盘中,这是一种不好的方法......所以我想做的是让第二个脚本以某种方式与服务器交互并告诉它启动一个关闭序列,该序列将干净地关闭所有线程、关闭和归档日志等。
现在我知道了atexit,并以这种方式对其进行了测试:
import atexit
def byebye(o):
o.write('stop')
o.flush()
o.close()
o = open('log','w')
o.write('start')
o.flush()
atexit.register(byebye, o)
while True:
pass
但是当我kill -9
的过程中,byebye()
并没有被解雇。我应该使用全能kill -9
以外的命令吗?我将如何关闭该过程?