import os
import sys
import time
import transaction
from ZODB import Connection
from ZODB.DB import DB
from ZEO import ClientStorage


def traceit(frame, event, arg):
    if event == "line":
        lineno = frame.f_lineno
        filename = frame.f_code.co_filename
        print "%s, line %i" %(filename, lineno)

    return traceit

def main():
    db = DB(ClientStorage.ClientStorage(('', 8100)))
    transaction.begin()
    conn = db.open()
    conn.root()['msg'] = 'Hello!'
    transaction.commit()
    conn.close()
    print 'Start: ' + db.open().root()['msg']

    pid = os.fork()
    if pid:
        # Old process
        for i in range(10):
            time.sleep(0.25)
            result = os.waitpid(pid, os.WNOHANG)
            if result[0]:
                break
        if not result[0]:
            os.kill(pid, 9)
            print 'process hung'

        # 1. Simply try to get the data from the database.
        #    Result: Original Entry.
        conn = db.open()
        print 'Original Process: ' + conn.root()['msg']
        conn.close()
        db.close()
        sys.exit(0)
    else:
        # New Process
        #import pdb; pdb.set_trace()
        sys.settrace(traceit)
        #db = DB(ClientStorage.ClientStorage(('', 8100)))
        transaction.begin()
        conn = db.open()
        print 'Forked Process: ' + conn.root()['msg']
        conn.root()['msg'] = 'Hello World!'
        transaction.commit()
        conn.close()
        sys.exit(0)

if __name__ == '__main__':
    main()
