http://qs321.pair.com?node_id=70173

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is there a easy way to test to see if a file is opened or being written to without writing a big function?

Replies are listed 'Best First'.
Re: File Test
by AgentM (Curate) on Apr 05, 2001 at 21:36 UTC
    Under UN*X? No. The big function would be making queries to either the FS or the kernel, depending on the OS.

    Under MacOS? No problem. See Mac::MoreFiles. A function already exists to do that. (MacOS supports mandatoy file locking.)

    Under AFS (AtheOS)? Node watching is supported and encouraged (cool stuff).

    Under NFS? Too much chance for race conditions- no way.

    Under VMS? I don't know.

    Under Win32? I don't care.

    If you come a across a situation where you need to know if a file is currently being used without some form of IPC, you're in bad shape- this is indicative of a poor design.

    AgentM Systems nor Nasca Enterprises nor Bone::Easy nor Macperl is responsible for the comments made by AgentM. Remember, you can build any logical system with NOR.
      Under UNIX, you could parse the output of the lsof program (if available).
        What happens when someone else starts reading the file while you are parsing lsof's output? Or stops reading it, for that matter.

        --
        $you = new YOU;
        honk() if $you->love(perl)

Re: File Test
by Masem (Monsignor) on Apr 05, 2001 at 21:40 UTC
    There's no standard way to do it, and while one could use lock files, any other program outside of yourself doesn't have to respect lock files (either creating them or obeying them).

    If you think the file is being written to as you work with it, you can always use stat to get the modify time of a file before and after some point in time; if it's different, you know the file's been written to. But if the other program has the file opened, but is idling and not writing anything, you won't be able to detect this.


    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
Re: File Test
by cmilfo (Hermit) on Jun 12, 2002 at 19:41 UTC
    On Unix, man fuser.