How To Use Shared Memory in PHP
PHP supports shared memory which can be used to store and retrieve data across processes. This is also another alternative way to communicate between php scripts. Normally shared memory is used for caching frequently used data in memory for php scripts on the same server. Let's see how we can use shared memory with a simple example.
How to create PHP shared memory and save a variable (array)
Here is a sample code with comments:
$key = 'mykey'; // Key to store data with
//Returns System V IPC key; 'My test' should be replaced by the pathname of an existing file
// as per manual. I found that even a non-existent file works fine.
// The second argument is project identifier; a single character of your choice
$shm_key = ftok('My test','P');
$data = shm_attach($shm_key); // Pointer to shared memory
// Sample data to store
$test = array("hello","angsuman","chakraborty");
shm_put_var($data,$inmem,$test); // Save the data in shared memory
print_r(shm_get_var($data,$mykey)); // Print the saved data
shm_detach($data); // Disconnects from shared memory segment; the data remains intact
How to fetch data from shared memory in PHP
$key = 'mykey';
$shm_key = ftok('My test','P');
$data = shm_attach($shm_key);
print_r(shm_get_var($data,$mykey));
shm_detach($data);
Notes:
1. The code has been tested on Linux only.
2. The arguments to ftok must be same to access the same shared memory from multiple scripts. For use in multiple processes within the same script file use __FILE__ as the first argument to ftok().
Filed under Enterprise Software, Headline News, How To, Linux, Open Source Software, PHP, Programming, Web |
|
RSS 2.0 |
Trackback this Article
|
Email this Article
You may also like to read |




































November 13th, 2007 at 12:05 pm
This was an interesting tutorial, nicely done I will have a go at trying this for my self.
Regards,
Lamonte Harris
November 13th, 2007 at 2:53 pm
It’s fantastic to see a PHP programmer who pays close attention to how much memory they’re using.
February 20th, 2008 at 3:26 am
this is wonderful code and i will test this under my system
thanks
June 14th, 2008 at 11:48 am
where is the code? I tried opening the page in both Firefox and IE, and code examples seem to be missing ?
June 14th, 2008 at 12:16 pm
@Adam
Thanks. I consider myself more as a Java developer
June 14th, 2008 at 12:21 pm
WordPress 2.5.1 screwed up my code. It is back again. Please refresh the page.