From 44ebd400cdabc4d2165155ab394f3711b131121a Mon Sep 17 00:00:00 2001 From: msincenselee Date: Sun, 1 Dec 2019 07:54:40 +0800 Subject: [PATCH] =?UTF-8?q?[=E6=96=B0=E5=8A=9F=E8=83=BD]=20=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E8=BF=9B=E7=A8=8BID=E8=BF=90=E8=A1=8C=E7=9B=91?= =?UTF-8?q?=E6=8E=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- vnpy/trader/util_pid.py | 77 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 vnpy/trader/util_pid.py diff --git a/vnpy/trader/util_pid.py b/vnpy/trader/util_pid.py new file mode 100644 index 00000000..1ee619bc --- /dev/null +++ b/vnpy/trader/util_pid.py @@ -0,0 +1,77 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +import os + +# 保存进程ID => logs/pid.txt +# 运行开始时,检查是否存在之前得pid进程 +# 一般使用与运行服务,且唯一进程 + +# 日志文件路径 +logs_path = os.path.abspath(os.path.join(os.getcwd(), 'logs')) +if not os.path.isdir(logs_path): + os.mkdir(logs_path) +assert os.path.isdir(logs_path) + +# 记录pid得文件 +pid_file = os.path.abspath(os.path.join(logs_path, 'pid.txt')) + + +def _check_pid(pid): + """ + 检查pid是否与当前进程pid一致 + :param pid: + :return: + """ + cur_pid = os.getpid() + if cur_pid != pid: + return False + return True + + +def _check_status(): + """ + 检查状态 + :return: + """ + if os.path.exists(pid_file): + with open(pid_file, 'r') as f: + pid = f.read().strip() + # print(pid) + if pid != "": + if _check_pid(pid): + return pid + return None + + +def _save_pid(log=True): + """ + 保存pid + :param log: + :return: + """ + pid = os.getpid() + if log: + print('pid={}'.format(pid)) + + with open(pid_file, 'w') as f: + f.write(str(pid)) + if log: + print(u'wrote pid file:{}'.format(pid_file)) + + +def update_pid(): + """ + 更新pid + :return: + """ + _save_pid(log=False) + + +# 执行检查 +if _check_status(): + import sys + print(u'another service is already running...', file=sys.stderr) + exit(0) + +_save_pid()