python 锁

#!/usr/bin/env python

#!coding=utf-8

 

#锁定操作

 

import socket , traceback , os, sys, fcntl, time

import signal

#fcntl

 

 

"""

flock(FH,LOCK_EX|LOCK_SH|LOCK_UN)

LOCK_EX 独占锁,排他锁

LOCK_SH 共享锁

LOCK_UN 对文件解锁

"""

def getlastaccess(fd , ip):

    fcntl.flock(fd, fcntl.LOCK_SH)  #

 

    try:

        fd.seek(0)

        for line in fd.readlines():

            fileip , assesstime = line.strip().split("|")

            if fileip == ip:

                return assesstime

        return None

    finally:

        print"in getlastaccess finally"

        fcntl.flock(fd, fcntl.LOCK_UN) #解除锁,释放锁

 

 

def writelastaccess(fd, ip):

    print fcntl.flock(fd, fcntl.LOCK_EX)

    records = []

    try:

        fd.seek(0)

        for line in fd.readlines():

            fileip , accesstime = line.strip().split("|")

            if fileip!=ip:

                records.append((fileip,accesstime))

        fd.seek(0)

        for fileip , accesstime in records + [(ip , time.asctime())]:

            fd.write("%s|%s\n" %(fileip, accesstime))

        fd.truncate()

    finally:

        print "in writelastaccess finally "

        fcntl.flock(fd, fcntl.LOCK_UN)

 

 

 

def reap(signum , stackframe):

    while 1:

        try:

            result = os.waitpid(-1, os.WNOHANG)

            if not result[0]:

                break

        except:

            break

        print "reaped child process %d"%(result[0])

 

 

host=''

port = 9002

 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

s.bind((host, port))

s.listen(1)

 

fd = open("lastaccess.txt", "w+")

 

while 1:

    try:

        clientsock, clientaddr = s.accept()

    except KeyboardInterrupt:

        raise

    except:

        traceback.print_exc()

        continue

 

 

    signal.signal(signal.SIGCHLD, reap)

 

    pid = os.fork()

 

    if pid:

        clientsock.close()

        continue

    else:

        s.close()

 

    try:

        print "got connection from %s ,servicing with pid %d"%\

        (clientsock.getpeername(), os.getpid())

        ip = clientsock.getpeername()[0]

        clientsock.sendall("welcome ,%s \n" % ip)

        last = getlastaccess(fd, ip)

 

        if last:

            clientsock.sendall("i last saw you at %s.\n" %last)

        else:

            clientsock.sendall("i've never seen you before.\n")

        writelastaccess(fd, ip)

        clientsock.sendall("i have noted your connection at %s.n"%\

         getlastaccess(fd, ip))

    except (KeyboardInterrupt, SystemExit):

        raise

    except:

        traceback.print_exc()

 

    #time.sleep(10)

    try:

        clientsock.close()

 

    except KeyboardInterrupt:

        raise

    except:

        traceback.print_exc()

    sys.exit()

 

 

你可能感兴趣的:(python)