tags:

views:

46

answers:

2

I've been looking around but I can't seem to find any implementation of POSIX named semaphores for PHP. The only thing I see is SysV semaphores.

(2 questions)

Is there any way to access named semaphores from PHP currently?

Are there any plans for future releases of PHP?

+1  A: 

Here is my "named" semaphore implementation, but i'm not sure if you're looking for a simple string to int converter.

/**
 * Generate a semaphore integer from a string/key
 *
 * @param string $identifier
 * @return int
 */
function sem_key($identifier) {
    $md5 = md5($identifier);
    $key = 0;
    for ($i = 0; $i < 32; $i++) { 
        $key += ord($md5{$i}) * $i;
    }
    return $key;
}
Bob Fanger
Interesting workaround. I actually played around with the flock() function and it was exactly what I needed, but I appreciate your answer.I'm new to StackOverflow (as you probably noticed). Is there any way to tag this question as "no longer in need of answer"? Or should I just mark your answer as "accepted answer"?
Ixai
You should answer your own question with the solution you used. And mark your own answer as "accepted answer"
Bob Fanger
+1  A: 

I guess the short answer would be NO, from my "research" I found there isn't a POSIX named semaphores implementation currently in PHP.

Bob Fanger posted an interesting workaround to convert strings to SysV semaphore keys, the downside is you have to implement this same algorithm in every code you need the semaphore.

What I ended up doing, though, was using flock() on a lock file.

PHP

# open an exclusive lock
$lock = fopen('/path/to/file.lock', 'w');
flock($lock, LOCK_EX);

# edit a file
$f = fopen ('/path/to/file.txt', 'a');
fwrite($f, "append through PHP\n");
fclose($f);

# unlock
flock($lock, LOCK_UN);
fclose($lock);

PERL

use Fcntl qw(:flock);

# open an exclusive lock
open LOCK, '>/path/to/file.lock';
flock LOCK, LOCK_EX;

# edit a file
open FILE, '>>/path/to/file.txt';
print FILE "append through PERL\n";
close FILE;

# unlock
flock LOCK, LOCK_UN;
close LOCK;

I know the extra lock file might seem as an overkill but you can only use LOCK_EX on write mode, and sometimes I only needed to read the file.

note: flock() works as an advisory file locking mechanism, if any other program tries to modify the file without calling flock() it will succeed.

Ixai