Tuesday, June 22, 2010

php file handle GC and flock

I was confused for a bit because I had code similar to this (details elided):


function myFunc() {
$h = fopen (MYLOCKFILE,"r");
return flock($h, LOCK_EX);
}


And when I would call it and sleep (e.g., myFunc();sleep 300;) and then run the same program in another shell the second shell wasn't blocking at the flock call.

strace showed an flock(4, LOCK_UN) being called in the first running instance. Apparently, since I don't return the handle nor do I assign it to a variable that's passed by reference, php decides that $h can be GCed immediately upon function return. That closes the file and releases the lock, so the second instance wouldn't block since there was no lock there.

No comments: