Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to see if a file is being written to?

Tags:

php

We have a FreeBSD server with samba that employees copy image files on to, which then get uploaded to our web servers (this way they don't have to mess with ftp). Sometimes, if the upload script is running at the same time as files are being copied, it can upload an incomplete file.

We fixed this by getting the list of files along with the file sizes, then waiting 5 seconds and rechecking the file sizes. If the sizes match then its save to upload, if they don't match it checks again in another 5 seconds.

This seems like an odd way to check if the files are being written to. is there a better, more simple way of doing this?

like image 493
Echo says Reinstate Monica Avatar asked May 04 '12 14:05

Echo says Reinstate Monica


2 Answers

Use a flock function http://php.net/flock - when writing a file obtain an exclusive lock flock($handle, LOCK_EX), after it is written release the lock flock($handle, LOCK_UN).

The upload script could try to obtain the exclusive writing lock too, if it succeeds it is Okay to move the file, otherwise no.

EDIT: Sorry, I forgot about the users copying the files to the server through samba... So there is no space to use flock while copying... But the upload script could still use flock($handle, LOCK_EX) to see, if it is successful or not.

like image 196
shadyyx Avatar answered Oct 04 '22 12:10

shadyyx


I recommend to shell_exec() smbstatus(1), e.g. smbstatus -LB to check for locked files

like image 26
Eugen Rieck Avatar answered Oct 04 '22 13:10

Eugen Rieck