Zend - The PHP Company




Miscellaneous

Add Code


Shared memory functions and examples  

Type: code fragment
Added by: joeldg
Entered: 14/10/2002
Last modified: 31/10/2001
Rating: - (fewer than 3 votes)
Views: 4282
Shared memory examples, there are few examples to be found just about anywhere on this subject, I wrote these up a few months ago and am posting them here in case anyone might need these.


<?
//shared memory example.. hope this helps
 
// return a memory hex segment for string..
// limit four chars in  Joel = 0x4a6f656c (joel is my name)
function memsegspot($str){
        
$str str_pad($str4"Z"); // Z = 5a
    
for ($a=0$a<4$a++){
      
$out1 substr($str$a 1); // walk through
      
$out .= dechex(ord($out1)); // ord returns dec, we need hex for shared memory segments
    
}//
    
return ("0x".$out); // prepend the 
}//end function

// memory location and size of location to alloc
function attachtomem($memloc$alloc){
     
$sem_id=sem_get($memloc1);
    
sem_acquire($sem_id);
    
$shm shm_attach($memloc$alloc);
    return 
$shm;
}
// end function
 
  
$test serialize("If you can read this, it is coming out of shared memory..");
  
$ms = ((strlen($test)+44)*2);
  
$sem_id sem_get(memsegspot("test"), 1);
   
sem_acquire($sem_id);
  
$smh shm_attach(memsegspot("test"), $ms);
  echo 
"Attached to shm # $smhn";
  
shm_put_var($smh$joi{md5($test)}, $test); // $shm_variable is the variable name, $test = the data
  
shm_put_var($smh$anotherserialize("some data"));
  echo 
"placed data in shm.n";
    
  
$out = @shm_get_var($smh, ${md5($test)});

  echo 
unserialize($out) . " n stored as: " md5($out)."n";
  @
shm_detach($sem_id);
  echo 
"detached from shared memory..n";
  echo 
$ms " bytes memory used.n";
?>


Usage Example




Rate This Script





Search



This Category All Categories