How to Check If a File Is Open by Another Process (Java/Linux)

How to check if a file is opened

If this

//Create file object 
File file = new File (fileName);

doesn't produce an exception, then the file was accessed correctly. However if you need to check if the file is being written to or if it's being otherwise accessed allready, you will need to check if it's locked.

File file = new File(fileName);
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

FileLock lock = channel.lock();
try {
lock = channel.tryLock();
System.out.print("file is not locked");
} catch (OverlappingFileLockException e) {
System.out.print("file is locked");
} finally {
lock.release();
}

Check if a file is not open nor being used by another process

An issue with trying to find out if a file is being used by another process is the possibility of a race condition. You could check a file, decide that it is not in use, then just before you open it another process (or thread) leaps in and grabs it (or even deletes it).

Ok, let's say you decide to live with that possibility and hope it does not occur. To check files in use by other processes is operating system dependant.

On Linux it is fairly easy, just iterate through the PIDs in /proc. Here is a generator that iterates over files in use for a specific PID:

def iterate_fds(pid):
dir = '/proc/'+str(pid)+'/fd'
if not os.access(dir,os.R_OK|os.X_OK): return

for fds in os.listdir(dir):
for fd in fds:
full_name = os.path.join(dir, fd)
try:
file = os.readlink(full_name)
if file == '/dev/null' or \
re.match(r'pipe:\[\d+\]',file) or \
re.match(r'socket:\[\d+\]',file):
file = None
except OSError as err:
if err.errno == 2:
file = None
else:
raise(err)

yield (fd,file)

On Windows it is not quite so straightforward, the APIs are not published. There is a sysinternals tool (handle.exe) that can be used, but I recommend the PyPi module psutil, which is portable (i.e., it runs on Linux as well, and probably on other OS):

import psutil

for proc in psutil.process_iter():
try:
# this returns the list of opened files by the current process
flist = proc.open_files()
if flist:
print(proc.pid,proc.name)
for nt in flist:
print("\t",nt.path)

# This catches a race condition where a process ends
# before we can examine its files
except psutil.NoSuchProcess as err:
print("****",err)

How to test if a file is open in Java?

There is no easy way in Java to go about this that will work reliably across different platforms. Depending on what you're trying to do, you might be able to patch together a series of try/catch statements which ostensibly work for most cases on most file systems, but you can never have full certainty that the next situation it encounters won't throw it off.

If you do end up going this route you want to ensure that when there is any doubt, it fails fast and doesn't get into a situation where it thinks a file is not open when it really is. My advice would be to see if there is any way you can possibly work around having to do this check.

How to check is a certain process is running - java on linux

A possible solution might be explorer the proc entries. Indeed, this is how top and others gain access to the list of running process.

I'm not completely sure if this is what your looking for, but it can give you some clue:

    import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class OpenFolder {
public static void main(String[] args) throws IOException {
System.out.println(findProcess("process_name_here"));
}

public static boolean findProcess(String processName) throws IOException {
String filePath = new String("");
File directory = new File("/proc");
File[] contents = directory.listFiles();
boolean found = false;
for (File f : contents) {
if (f.getAbsolutePath().matches("\\/proc\\/\\d+")) {
filePath = f.getAbsolutePath().concat("/status");
if (readFile(filePath, processName))
found = true;
}
}
return found;
}

public static boolean readFile(String filename, String processName)
throws IOException {
FileInputStream fstream = new FileInputStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine().split(":")[1].trim();
br.close();
if (strLine.equals(processName))
return true;
else
return false;
}
}

Checking if file is completely written

Does the producer process close the file when its finished writing? If so, trying to open the file in the consumer process with an exclusive lock will fail if the producer process is still producing.



Related Topics



Leave a reply



Submit