PHP provides a handy support for System V IPC functions in the Semaphore module. Let’s have a look at the functions responsible for handling shared memory. They can be used to implement a simple way of exchanging information between the processes.
To see if your PHP installation supports IPC, run:
% php -i | grep sysv
If PHP was compiled with –enable-sysvmsg you should see something like this:
sysvmsg support => enabled
To actually user the shared memory we will:
- Initialize shared memory with a size and a key. The key will be used as identifier of our shared memory block.
- Store a variable in the shared memory. We will use another key to identify our variable within shared memory.
- Read from shared memory and destroy it
I’m using CLI interface for all the examples below. The code:
Call to shm_attach above creates shared memory identified by number 0×12345 of the size of 512 bytes. It returns a handle that you then can use to operate on the shared memory. The handle is a resource of type sysvshm.
In the example above I did not destroy (remove) the shared memory. It means that it should stay on your system even after the script finishes. To “see” it on Linux you can use ipcs command:
Pay attention to the perms column. The default value (666) means that all other processes running on the same machine have read/write access the shared memory you just created.
Finally, use shm_remove($shm_id) to free the memory. All data will be destroyed.