How to check whether a file is being opened by other programs in Perlscript?

Discussion in 'Perl Misc' started by Kuhl, Nov 13, 2008.

  1. Kuhl

    Kuhl Guest

    Hi, in my Perl script, I need to operate on a file. But I need to
    check whether the file is being opened by any other programs, for
    example vi, and then my operation will be performed based on this
    check result. How to do this check? Thanks.
    Kuhl, Nov 13, 2008
    1. Advertisements

  2. Kuhl

    toralf Guest

    perldoc -f flock
    toralf, Nov 13, 2008
    1. Advertisements

  3. The result of this check is absolutely worthless: before you use the
    result of the check, the closed file may be opened, or the open file may
    be closed. The file may even cease to exist before you do anything.

    Besides: vim (VI iMproved) opens the file, reads it, then closes it
    again, then you work on some copy (start editing a file, then, on
    another tty look at the editor's open files in /proc/<pidofeditor>/fd).
    When you save the result, vi may very create a new file rather than
    rewrite the old file (ls -lisa <somefile>; vi <somefile> # and change
    it, then save it; ls -lisa <somefile> # the first number is the inode).

    It's a similar issue with trying to use the existence of a file as a
    locking mechanism: perldoc -q file.lock

    Josef Moellers, Nov 13, 2008
  4. Depending on your OS and the file system there may be no way unless the
    programs cooperate, see 'perldoc -q lock':

    How can I lock a file?

    Jürgen Exner, Nov 13, 2008
  5. Kuhl

    Tim Greer Guest

    As others have suggested, look into using file locking. Just keep in
    mind, that any program or process that will be reading the file also
    needs to obey the same rules with locking. As the saying goes with
    file locking "If any single program or process reads, opens or writes
    to the file without following the rules, all bets are off".
    Tim Greer, Nov 13, 2008
  6. Kuhl

    WANG Cong Guest

    perl -e 'print qx{/usr/sbin/lsof | grep foo.cfg}, "\n";'
    WANG Cong, Nov 13, 2008
  7. Kuhl

    Tim Greer Guest

    Except that won't help if the file is opened/read right after that ran,
    before the perl script does its work. That may create a race
    Tim Greer, Nov 13, 2008
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.