PHP Conference Japan 2024

shmop_write

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

shmop_write將資料寫入共享記憶體區塊

說明

shmop_write(Shmop $shmop, 字串 $data, 整數 $offset): 整數

shmop_write() 會將字串寫入共享記憶體區塊。

參數

shmop

shmop_open() 建立的共享記憶體區塊識別碼

資料 (data)

要寫入共享記憶體區塊的字串

偏移量 (offset)

指定在共享記憶體區段內開始寫入資料的位置。偏移量必須大於或等於零,且小於或等於共享記憶體區段的實際大小。

返回值

已寫入 data 的大小。

錯誤/例外

如果 offset 超出範圍,或是嘗試寫入唯讀的共享記憶體區段,則會拋出 ValueError

更新日誌

版本 說明
8.0.0 在 PHP 8.0.0 之前,失敗時會返回 false
8.0.0 shmop 現在需要一個 Shmop 實例;以前需要的是 resource

範例

範例 #1 寫入共享記憶體區塊

<?php
$shm_bytes_written
= shmop_write($shm_id, $my_string, 0);
?>

此範例會將 $my_string 內的資料寫入共享記憶體區塊,$shm_bytes_written 將包含已寫入的位元組數。

參見

新增註釋

使用者貢獻的註釋 2 則註釋

mark at manngo dot net
1 年前
您可能想要做的一件事是用較短的字串替換舊字串,或者完全清除字串。

要替換字串,您可以用零位元組填充您正在寫入的字串

<?php
// $shmid 來自 shmop_open()
$size = 128;
$string = 'something';

// 寫入
$string = str_pad($string, $size, "\0");
shmop_write($shmid, $string, 0);

// 讀取
print rtrim(shmop_read($shmid,0,$size), "\0");

// 清除
$string = str_repeat("\0",$size);
shmop_write($shmid, $string, 0);
?>
radupb at yahoo dot com
4 年前
我想 pack 和 unpack 函式是用於將資料編碼/解碼為二進位字串,方便 shmop_write/shmop_read 使用的便捷函式。範例:

$format='LLLLSSCCCC'; // pack 的資料格式
$key=1;
if( !($shmid=shmop_open($key,'n',0660,30)) )
die('shmop_open 失敗。');

//我要編碼的資料
$hd=array('ALIVE1'=>1,'ALIVE2'=>2,'ALIVE3'=>3,'ALIVE4'=>4,
'CRTPTR'=>5,'CRTSEQ'=>6,
'CTW'=>7,'LOCK'=>8,'PLAY'=>9,'MISS'=>10);
);

$tmp=pack( $format, $hd['ALIVE1'],$hd['ALIVE2'],$hd['ALIVE3'],$hd['ALIVE4'], $hd['CRTPTR'],$hd['CRTSEQ'],$hd['CTW'],$hd['LOCK'],$hd['PLAY'],$hd['MISS'] );

if( ($w=shmop_write($shmid,$tmp,0))!=24 )
die('寫入錯誤 $w='.$w);

從其他程序讀取:
$key=1;
if( !($shmid=shmop_open($key,'w',0,0)) )
die('shmop_open 失敗。');

$formatR='L4ALIVE/SCRTPTR/SCRTSEQ/CCTW/CLOCK/CPLAY/CMISS'; // unpack 的資料格式

$hd=unpack( $formatR, shmop_read( $shmid,0,24) );
echo'hd:<pre>';print_r($hd);echo'</pre>';
To Top