doucheng2053 2014-06-20 04:37
浏览 98

如何使用PHP清除共享内存?

I want to ask about why after I use shmop_delete($shmid) and shmop_close($shmid) there is nothing happen? the first string is still attaced.

This is my php code: $key = 864; $mode = 'c'; $permission = 0644; $size = 1024;

$shmid = shmop_open($key, $mode, $permission, 1024);

$string = "Hello World !!!";

shmop_write($shmid, $string, 0);

$size = shmop_size($shmid);
echo shmop_read($shmid, 0, $size);

shmop_delete($shmid);
shmop_close($shmid);

First Result: Hello World !!!

Then I change $string = "TEST".

After that I run the code again with result : TESTo World !!! (Unwanted Result). The result I want is : TEST

why the 'o World !!!' is still attached although I already did shmop_delete and shmop_close? And How I can erase it from Shared Memory? Thx...

  • 写回答

2条回答 默认 最新

  • dongzhang1839 2014-06-20 05:14
    关注

    When you first write "Hello World" it's writing the length of those 11 chars. When "Test" is written, it only writes the length of "Test" into the shared memory. That is why the rest of the string is still attached. One potential solution is to take the length written like so:

    $shm_bytes_written = shmop_write($shmid, $string, 0);

    and pad the next string to that length. Or I guess you could write the entire size of the shared block, but that's probably not what you want.

    Edit:

    The code should be something like this (not tested nor compiled). This is for ASCII. If you're using UTF-8, you'll need to handle getting the string length a bit differently. Hopefully you get the idea

    $shmid = shmop_open($key, $mode, $permission, 1024);
    
    $string = "Hello World !!!";
    
    $s1bytes = strlen( $string );
    
    $shm_bytes_written = shmop_write($shmid, $string, 0);
    
    $string2 = "Test";
    
    $padLen = strlen( $string ) - strlen( $string2 );
    
    $s2Pad = str_pad( "Test", $padLen );
    
    $shm_bytes_written = shmop_write($shmid, $s2Pad, 0);
    
    $size = shmop_size($shmid);
    echo shmop_read($shmid, 0, $size);
    
    shmop_delete($shmid);
    shmop_close($shmid);
    
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法