How can I create a non-file lock in PHP?

折月煮酒 提交于 2019-12-02 20:00:48

问题


I have a maintenance script in PHP that updates and repairs the database. In theory, running two scripts simultaneously shouldn't be a problem, but I want to be extra safe by putting a lock in a variable in PHP. The problem, of course, is that I can't store it in a $_SESSION variable because sessions only apply to one user.

Is there any way I can store this lock in a variable? I'd prefer to not create and delete a file in case the server dies in the middle of the script.


回答1:


MySQL has GET_LOCK() function.




回答2:


Since you're working with the database, you can lock the tables you need while the script runs. This will ensure exclusive database access.




回答3:


Is there any way I can store this lock in a variable?

A variable is local to the current instance of php - so its an even worse solution than keeping it in the session.

I'd prefer to not create and delete a file in case the server dies in the middle of the script.

It's still probably the best place to put it. If the repair script does not complete then you probably want to step in and manually ensure that the data is consistent - you should also be blocking all other access to the resource betwen the time the operation starts and finishes successfully.

If its running from the command prompt, then you could search the process list:

$cmd=$argv[0];
$pid=getmypid();
$find="ps -ef | grep $cmd | grep -v grep | grep -v $pid";
$others=`$find`;

But this still carries the risk that the previous attempt failed and the data is corrupt.

C.



来源:https://stackoverflow.com/questions/3446395/how-can-i-create-a-non-file-lock-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!