you want, as long as all programs that need to access this particular semaphore use the same
key. If a semaphore with the specified key doesn't already exist, it's created, the maximum
number of processes that can access the semaphore is set to the second argument of
(in this case,
), and the semaphore's permissions are set to
third argument (
). These permissions work just like file permissions, so
the user that created the semaphore can read it and write to it. In this context, user doesn't
just mean the process that created the semaphore but any process with the same user ID.
should be appropriate for most uses, in which web server processes run
as the same user.
returns an identifier that points to the underlying system semaphore. Use this ID
to gain control of the semaphore with
. This function waits until the
semaphore can be acquired (perhaps waiting until other processes release the semaphore)
and then returns
. It returns
on error. Errors include invalid permissions or not
enough memory to create the semaphore. Once the semaphore is acquired, you can read from
the shared memory segment.
First, establish a link to the particular shared memory segment with
, the first argument to
is an integer key. This time,
however it identifies the desired segment, not the semaphore. If the segment with the
specified key doesn't exist, the other arguments create it. The second argument (
the size in bytes of the segment, and the last argument (
) are the permissions on the
creates a 16K shared memory segment that can
be read from and written to only by the user who created it. The function returns the identifier
you need to read from and write to the shared memory segment.
After attaching to the segment, pull variables out of it with
. This looks in the shared memory segment identified by
the value of the variable called
. You can store any type of variable in shared
memory. Once the variable is retrieved, it can be operated on like other variables.
puts the value of
into the shared memory segment as a variable called
You're now done with the shared memory statement. Detach from it with
and release the semaphore with
so another process can use it.
Shared memory's chief advantage is that it's fast. But since it's stored in RAM, it can't hold too
much data, and it doesn't persist when a machine is rebooted (unless you take special steps to
write the information in shared memory to disk before shutdown and then load it into memory
again at startup). Also, shared memory is not available on Windows.
5.7.4 See Also