import os
def create_pid_file(pid_file_path):
"""
创建一个PID文件,将当前进程的PID写入指定路径的文件中。
参数:
pid_file_path (str): PID文件的路径
返回:
None
"""
pid = os.getpid()
with open(pid_file_path, 'w') as f:
f.write(str(pid))
print(f"PID {pid} has been written to {pid_file_path}")
def check_pid_file(pid_file_path):
"""
检查PID文件是否存在,并验证其中的PID是否仍然有效(即对应的进程是否仍在运行)。
参数:
pid_file_path (str): PID文件的路径
返回:
bool: 如果PID文件存在且对应的进程仍在运行,则返回True;否则返回False
"""
if not os.path.exists(pid_file_path):
return False
with open(pid_file_path, 'r') as f:
pid = int(f.read().strip())
try:
# 尝试发送信号0,以检查进程是否存在
os.kill(pid, 0)
return True
except OSError:
return False
# 示例用法
pid_file = '/tmp/myapp.pid'
if not check_pid_file(pid_file):
create_pid_file(pid_file)
else:
print("Another instance of the application is already running.")
False,否则返回 True。希望这段代码和解释对你有帮助!
上一篇:python async def
下一篇:python 设置全局变量
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站