dongxiai3003 2013-08-13 23:24
浏览 32
已采纳

脚本过早终止后,PHP共享内存变量仍然存在

I'm attempting to implement a simple non-blocking semaphore in PHP using the built-in shared memory functions. My script essentially looks like this:

$key = ftok(__FILE__, 'A');

$shmId = shm_attach($key);
$runningKey = 37238383940234;

// die now if the script is already running
if (shm_has_var($shmId, $runningKey)) {
    echo "Another instance is running
";
    exit;
}

// tell other instances that I'm running so that they die
shm_put_var($shmId, $runningKey, true);

sleep(20);

// drop shared memory key
shm_remove_var($shmId, $runningKey);

// terminate script
exit;

This works great as long as the script starts and ends normally. But, suppose the script died unexpectedly while it was running (after shm_put_var(), but before shm_remove_var()). For example, the process is killed by control-C or sent a SIGTERM. My tests have shown that when the script is re-started, the shared memory variable retains the value set by the now-dead instance. I can understand why this might be. However, I'm looking for a workaround, or perhaps some advice on an alternate approach.

My goal is a non-blocking semaphore that will keep multiple instances of the same CLI script from piling up on each other, while at the same time accounting for the case where a script sets the semaphore and dies before it has a chance to clear it.

Much thanks!

  • 写回答

1条回答 默认 最新

  • dtyz76562 2013-08-13 23:27
    关注

    Since you're dealing with locks between processes (as opposed to, let's say, PHP requests running on the same process), why not just use flock() over a dummy file (the path of which will act as the semaphore key)? The OS takes care of automatically releasing the lock if the process dies for whatever reason.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大