最近有需求希望进程启动的时候能kill掉已经运行的实例
#!/usr/bin/env python
# encoding: utf-8
import time
import os
import sys
import subprocess
def killOldProcess():
# kill 已有的进程id
with open('pid.txt', 'a+') as f:
old_pid = f.readline()
if old_pid :
# 确定进程id是运行的当前程序,防止误杀
ps_info = os.popen("ps -ef | grep %s | awk '{print $2}'" % __file__)
if old_pid in ps_info:
os.system('kill -9 %s' % old_pid)
# 保存当前进程id
with open('pid.txt', 'w') as f :
f.write('%d\n' % os.getpid())
if __name__ == '__main__':
killOldProcess()
while True :
time.sleep(1)