lang2
lang2

Reputation: 11966

lock file between C and php

Although the title mentions file, it doesn't have to be a file. Any locking mechanism would do.

Here is the situation: I have a daemon process written in C, and a web page in php. I'd like to have a way of mutual locking so that under certain situation, the C daemon would lock a file and php detects the situation and tells the client side that the system is busy.

Is there an easy way of doing this?

Thanks,

Upvotes: 1

Views: 447

Answers (4)

CoreyStup
CoreyStup

Reputation: 1488

Do you only want PHP to detect that the daemon is busy? Or do you actually want them to wait on each other? Using an exclusive lock would have the downside that the C daemon will have to wait for any and all PHP instances to finish their work before it can grab its lock and continue on.

If you're only looking to detect that the C daemon is busy (ie, only in one direction), just testing for the existance of a busy token file (or semaphore, or shared memory object - platform dependant) might be a better option. Creating files tends to be more expensive than just setting a simple flag in shared memory however.

Upvotes: 1

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99921

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

Upvotes: 3

mfonda
mfonda

Reputation: 8003

You could have your daemon create a file when busy, and remove it when not, then in PHP do something like:

if (file_exists('/path/to/file')) {
    echo 'System busy';
}

Upvotes: 2

Linus Kleen
Linus Kleen

Reputation: 34632

If your PHP application is database driven, it should be easy to update a certain column of that database to indicate "the system is busy".

Your cronjob would set and reset this flag and your PHP application can read its value.

Upvotes: 1

Related Questions