开发者

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

开发者 https://www.devze.com 2023-01-11 09:01 出处:网络
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 vari

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 t开发者_开发问答hat 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.


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


MySQL has GET_LOCK() function.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消