flock trouble

Seb sebastianthegreatful at gmail.com
Mon Sep 8 15:15:17 CEST 2008


I'm trying to implement a file server using the code below. However
the locking doesn't work. I can delete while put'ing a file.

Anyone got an idea about why?

best regards,
seb




#! /usr/bin/env python

import Pyro.core, Pyro.naming
from Pyro.errors import PyroError, NamingError
import sys
import urllib
import os
import fcntl

class fileServer(Pyro.core.ObjBase):
	basePath = "/home/snot/diku/dist/opg2/files_to_serve"

	def __init__(self):
		Pyro.core.ObjBase.__init__(self)
		self.basePath = self.basePath.strip("..")
		if not os.path.isdir(self.basePath) or
os.path.islink(self.basePath):
			raise "invalid path"

	def get(self, uri):
		f = open(self.basePath + uri, 'r+')
		fcntl.flock(f, fcntl.LOCK_SH)
		data = f.read()
		fcntl.flock(f, fcntl.LOCK_UN)
		f.close()
		return data

	def put(self, uri, payload):
		f = open(self.basePath + urllib.unquote_plus(uri), 'w')
		fcntl.flock(f, fcntl.LOCK_EX)
		f.truncate()
		f.write(payload)
		fcntl.flock(f, fcntl.LOCK_UN)
		f.close()

	def delete(self, uri):
		f = open(self.basePath + urllib.unquote_plus(uri), 'w')
		fcntl.flock(f, fcntl.LOCK_EX)
		os.unlink(self.basePath + uri)
		fcntl.flock(f, fcntl.LOCK_UN)
		f.close()

try:
	Pyro.core.initServer()
	daemon = Pyro.core.Daemon()
	locator = Pyro.naming.NameServerLocator()
	print 'Searching for Name Server...'
	try:
		ns = locator.getNS()
	except Pyro.errors.PyroError, message:
		print message
		sys.exit(1)

	daemon.useNameServer(ns)

	try:
		ns.unregister("fileServer")
	except NamingError:
		pass

	uri = daemon.connect(fileServer(), "fileServer")

	print "The daemon runs on port:", daemon.port
	print "The object's uri is:", uri

	daemon.requestLoop()
except KeyboardInterrupt:
	ns.unregister("fileServer")
	print "ctrl + c pressed"




More information about the Python-list mailing list