Wednesday, July 9, 2014

File handle not remaining valid in a property; CakePhp 2x

 I'm using the File Utility to read a file. I need to work with the file in some other methods and want to prevent access to it during the process, so I'm trying to get an exclusive lock on the file.

That seems to work fine... but while I have the file open and 'locked' I can make another File object for it and open and lock that also. That would be bad!

What I've found so far, if I examine the handle property of the file object while I'm in the readProcessed() method (shown below) I get something like:

resource(92, stream)

If I examine that same property from the code that instantiates NotificationFileHandler and calls readProcessed(), I see something like:

resource(92, Unknown)

This looks like some sort of scope problem, but I can't really understand why that should be or what I'm doing wrong.

// the method in question.
class NotificationFileHandler {

    * Read the processed file
     *
     * This method locks the processed file while reading and handling
     * It includes a 20 second wait routine to attempt to process the file
     * if it is already in use
     *
     * @return mixed FALSE if fail, the data in array form is successful
     */
    public function readProcessed() {
        $this->processedFile = new File($this->processedPath);
        $this->processedFile->open();
        $t = time()+20;
        while ($t > time() && $this->processedFile->lock != LOCK_EX){
            if(flock($this->processedFile->handle, LOCK_EX)){
                $this->processedFile->lock = LOCK_EX;
            }
        }
        if($this->processedFile->lock != LOCK_EX){
            return FALSE;
        }
        return $this->processedFile->read();
    }

}

// the calling code snippet
        $note = new NotificationFileHandler();
        $note->readProcessed();

       // this should return false but succeeds instead
        $intruder = new NotificationFileHandler();
        $intruder->readProcessed();


 Don

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: