ベンフィニーのロックファイルのようなものをすでに使用しているので
例:
from lockfile.pidlockfile import PIDLockFile
lock = PIDLockFile('somefile')
lock.acquire(timeout=3600)
#do stuff
lock.release()
実行中のデーモンと通信したい場合は、デーモンにソケットをリッスンさせてから、生成されたプロセスからデータをソケットに送信する必要があります。(f.ex a udpソケット)
したがって、デーモンでは:
import socket
import traceback
import Queue
import threading
import sys
hostname = 'localhost'
port = 12368
#your lockfile magick here
# if you want one script to run each time, put client code here instead of seperate script
#if already running somehwere:
#message = "hello"
#sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
#sock.sendto( message, (hostname, port) )
#sys.exit(0)
que = Queue.Queue(0)
socket_ = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket_.bind((hostname, port))
class MyThread(threading.Thread):
def run(self):
while True: #maybe add some timeout here, so this process closes after a while
# but only stop if que.empty()
message = que.get()
print "handling message: %s" % message
#handle message
t = MyThread()
t.start()
while True:
try:
#blocking call
message, _ = socket_.recvfrom(8192) #buffer size
print "received message: %s" % message
#queue message
que.put(message)
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
クライアントで:
import socket
hostname = 'localhost'
port = 12368
message = "hello"
sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
sock.sendto( message, (hostname, port) )
これらすべてを同じマシンで実行している場合は、ホスト名に「localhost」を使用できます。
一方、ソケットの代わりにマルチプロセスパイプを使用するのが適切な方法かもしれませんが、私はまだそれらの経験がありません。このセットアップには、サーバーとクライアントを別のマシンで実行できるという追加の利点があります。