in reply to flock issue

You must open a file with write permission in order to secure an exclusive lock. Also, you should be checking the result of your open calls. You can use the read/write mode "+<" to open it for writing without clobbering anything that is there. Use seek to move about once you have opened it so.