isBusy

Checks if a file is busy or not. As Standard Additions’ “busy status” is not allways reliable, this handler checks if needed if the file is or not opened for access by other process.

OS version: OS X

(*
isBusy
Checks if you can write to a file or not (if it is opened for access by other process).

Parameters:
f: file path, alias, posix path

Example:
isBusy("path:to:file.txt") --> false
*)

to isBusy(f)
	set f to f as Unicode text
	if f does not contain ":" then set f to POSIX file f as Unicode text
	
	if busy status of (info for alias f) then return true
	
	--> but some times this is not good enough
	try
		open for access file f with write permission
		close access result
		return false
	on error
		return true
	end try
end isBusy

property |version| : 1.0
property |from| : "jfileLib"
property author : "Pescados Software · PescadosWeb.com"
property |date| : date "sábado, 24 julio 2004 00:00:00"
property license : "freeware, open-source"

As I have verified, the script provided above works reliably, but only checks whether something is being written to the file by another process (that is, if the file is opened for WRITE access). For testing, I ran the song (MP3 file) in VLC.app.

For those who would like to check whether a file is opened (by some process) for READ or WRITE access, I suggest the following method. It is a little slower, but gives a guaranteed result:
 

-- Check if the file is used (opened for Read or Write access, t.e. busy) by other process
isFileBusy(choose file)

on isFileBusy(theAlias)
	local thePath, command, err
	set thePath to quoted form of (POSIX path of theAlias)
	try
		set command to "if ( lsof -Fp " & thePath & " | grep -q p[0-9]* ) then echo 'file is busy'; else echo 'not busy';fi"
		if (do shell script command) is "file is busy" then return true
		return false
	on error err
		display dialog ("Error: isFileBusy " & err) giving up after 5
	end try
end isFileBusy

 

1 Like