PracticeDev/study_python/tcp_relay-master/singletest.py

71 lines
1.3 KiB
Python
Executable File

#!/usr/bin/python
import os
import time
import sys
import logging
import exceptions
import fcntl
PID_FILE="TCP_RELAY.PID"
def create_pid_file():
pid = -1
pid = os.getpid()
f = open(PID_FILE,'w')
f.write(str(pid))
def compare_pid(pid):
PS_CMD = "ps -ef|awk '{print $2}'|grep "
PS_CMD = PS_CMD + pid
fd=os.popen(PS_CMD,"r")
pid_string = fd.read()
#print(pid_string)
if pid_string:
#print(pid_string)
bRun = 1
return bRun
else:
bRun = 0
return bRun
'''
def single_test():
bRun = 0
try:
fd=open(PID_FILE,'r')
except IOError:
print("PID File doesn't exist,create one")
create_pid_file()
return bRun
if fd:
old_pid = fd.readline()
print("already exist pid=%s"%old_pid)
bRun = compare_pid(old_pid)
if bRun == 1:
print("The task is already running")
print("Exit")
else:
print("No existing running task")
print("Continue executing")
create_pid_file()
return bRun
'''
def single_test():
global pidfile
pidfile = open(PID_FILE, "w")
try:
fcntl.lockf(pidfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print("The task is already running...")
sys.exit(0)