Fatal error: Call to undefined function sem_get()
Asked Answered
A

2

7

I'm new to PHP and I'm trying to run code I got from someone else on my Windows development machine. I installed PHP 5 and Apache 2.2, but when I try to run it I get the error:

Fatal error: Call to undefined function sem_get()

The line it's being thrown from is:

private function UpdateCounter($semkey, $memkey, $count)
{
    $sem_h = sem_get($semkey, 1);//this line is the problem
    ...
}
Assumptive answered 9/3, 2011 at 19:42 Comment(0)
Y
10

The sem_get() function is provided by the Semaphore, Shared Memory and IPC component.

Quoting the introduction of it's manual section :

This extension is not available on Windows platforms.

Yorker answered 9/3, 2011 at 19:45 Comment(1)
If the manual states it's not available on Windows, I don't think there is -- except using Linux ;-)Yorker
C
9

I don't know if that will work as expected, but I found a workaround for sem_get on Windows:

if (!function_exists('sem_get')) {
    function sem_get($key) {
        return fopen(__FILE__ . '.sem.' . $key, 'w+');
    }
    function sem_acquire($sem_id) {
        return flock($sem_id, LOCK_EX);
    }
    function sem_release($sem_id) {
        return flock($sem_id, LOCK_UN);
    }
}

Also, I needed ftok on Windows too:

if( !function_exists('ftok') )
{
    function ftok($filename = "", $proj = "")
    {
        if( empty($filename) || !file_exists($filename) )
        {
            return -1;
        }
        else
        {
            $filename = $filename . (string) $proj;
            for($key = array(); sizeof($key) < strlen($filename); $key[] = ord(substr($filename, sizeof($key), 1)));
            return dechex(array_sum($key));
        }
    }
}
Corrective answered 28/7, 2013 at 19:11 Comment(3)
+1 for providing function_exists here so I can ignore this in my development environment (Windows).Contorted
flock in the example will block until the lock is released. It's a good idea to add LOCK_NB flag so that it doesn't block the execution if it cannot lock the file immediately.Fuse
Sorry for offtop. But use lock for files is bad idea. If you forgot (or your script will fail exit) unlock file before exit your script, then you can't lock it in new script execution. With semaphores it not possible.Ranite

© 2022 - 2024 — McMap. All rights reserved.