在C和php之间锁定文件 [英] lock file between C and php

查看:82
本文介绍了在C和php之间锁定文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管标题提到了文件,但它不一定是文件.任何锁定机制都可以.

这里是情况:我有一个用C编写的守护进程,一个用php编写的网页.我希望有一种相互锁定的方法,以便在某些情况下,C守护程序可以锁定文件,而php会检测到这种情况,并告诉客户端系统正忙.

有一种简单的方法吗?

谢谢

解决方案

flock 正确执行. /p>

在您的PHP脚本中,使用非阻塞锁:

$fd = fopen('/var/run/lock.file', 'r+');
if (!flock($fd, LOCK_SH | LOCK_NB, $wouldblock) && $wouldblock) {
    // buzy
}

LOCK_NB标志使此调用成为非阻塞.如果文件被独占锁定,它将立即返回.允许多个页面同时锁定文件.

您可以使用以下方式解除锁定

flock($fd, LOCK_UN);

在您的C守护程序中,使用阻止锁和排他锁:

flock(fd, LOCK_EX); // This will wait until no page has locked the file

请参阅PHP的 flock() 文档和C的 解决方案

flock does it properly.

In your PHP script, use a non-blocking lock:

$fd = fopen('/var/run/lock.file', 'r+');
if (!flock($fd, LOCK_SH | LOCK_NB, $wouldblock) && $wouldblock) {
    // buzy
}

The LOCK_NB flag make this call non blocking. If the file is locked exclusively, it will return immediately. Multiple pages will be allowed to lock the file at the same time.

You can release the lock with

flock($fd, LOCK_UN);

In your C daemon, use a blocking and exclusive lock:

flock(fd, LOCK_EX); // This will wait until no page has locked the file

See PHP's flock() documentation and C's one

这篇关于在C和php之间锁定文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆