in reply to file used by process

You could try to open the file for appending. If the open fails then either the file can't be created/opened due to permissions problems (or a bad file name or whatever) or it is locked (maybe depending on the OS). Once opened you can use flock to attempt to grab an exclusive lock (LOCK_EX) and again if that fails it is probably already locked.

True laziness is hard work

Replies are listed 'Best First'.
Re^2: file used by process
by farhan (Novice) on Sep 09, 2010 at 05:51 UTC
    Thanks Grandfather for replying.

    #!/usr/bin/perl
    open(FH , ">>/var/log/apache2/access.log") or die "cant";

    print FH "This is test\n";

    close(FH);
    But it appends to the file access.log but this file is being used by the process of apache

    root@cu:~# lsof|grep access.log
    apache2 1115 www-data 8w REG 9,4 30362650 2719854 /var/log/apache2/access.log
    apache2 1115 www-data 9w REG 9,4 30362650 2719854 /var/log/apache2/access.log
    apache2 2773 www-data 8w REG 9,4 30362650 2719854 /var/log/apache2/access.log
    apache2 2773 www-data 9w REG 9,4 30362650 2719854 /var/log/apache2/access.log

    If this file is being used by apache I shouldn't have been able to append the file but I appended it

      Which is why I said "or it is locked (maybe depending on the OS)" - it's an OS dependent behaviour. It's also why I went on to suggest you could use flock, although others have pointed out that that may not do quite what you want either.

      True laziness is hard work
      If you think it through, it is entirely correct that Apache allows you to open this file.

      Think what would happen if Apache kept an exclusive lock on this file: nobody would ever be able to even read the file, unless they would have shutdown the webserver!

      Of course writing to the Apache log-file is not advised, but it can hardly be considered Apache's fault that you are trying to destroy its log.

      You might answer that reading a file is different from writing and the locking mechanism should account for that and a shared lock should just do that (the process holding the lock can read/write, all others can only read). Alas, locks are just advisory by nature, so you may ignore them at your own peril.

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James