mutualExclusion.php
1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
require_once dirname(__FILE__) . '/../config.php';
require_once LIBDIR . 'errException.php';
function acquireLock ($lockFile, $csId)
{
$fName = $lockFile . $csId . '.lck';
$lock = NULL;
setErrExceptionMapping ();
$lockHandle = fopen ($fName, 'w');
// if available use semaphores for mutual exclusion because flock
// doesn't work reliably in threaded environments.
if (function_exists ('sem_get'))
{
$lock = sem_get (ftok ($fName, $csId), 1, 0644, TRUE);
$state = sem_acquire ($lock);
while ($state === FALSE)
$state = sem_acquire ($lock);
}
else
{
$state = flock ($lock, LOCK_EX);
while ($state === FALSE)
$state = flock ($lock, LOCK_EX);
}
// Here one could write informations in the lockfile...time, pid, etc.
fwrite ($lockHandle, session_id () . '::' . time ());
fflush ($lockHandle);
resetErrExceptionMapping ();
$userAbort = ignore_user_abort(TRUE);
return array ($lockHandle, $lock, $userAbort);
}
function releaseLock ($lock)
{
setErrExceptionMapping ();
if ($lock[1] !== NULL)
sem_release ($lock[1]);
ftruncate ($lock[0], 0);
fclose ($lock[0]);
resetErrExceptionMapping ();
ignore_user_abort($lock[2]);
}
?>