asachet
asachet

Reputation: 6921

check if file is available (not in use by another process) with R

How can I check if a file is, not only existing, but not used by another process at the moment?

The context is that I am writing my output to the same file every time I run my code. The output is created with an external tool via a call to system().

When the file was opened (because I wanted to check its content) and not closed before the system() call, eveything just hangs. I would like to check that the file is available before overwriting it.

I am looking for a R solution, but I am also interested in a console (system() call) solution if it is interfaced with R. My work laptop has windows with cygwin so DOS and UNIX command are ok.

Upvotes: 0

Views: 1347

Answers (2)

MS Berends
MS Berends

Reputation: 5269

I think you should check if R can write to the file, so check for open = "w":

file.opened <- function(path) {
  suppressWarnings(
    "try-error" %in% class(
      try(file(path, 
               open = "w"), 
          silent = TRUE
      )
    )
  )
}

Will return TRUE when a user has opened the file and FALSE otherwise.

Upvotes: 0

Minnow
Minnow

Reputation: 1821

You can use the lsof from unix command line to determine which files are open at the moment:

For example:

lsof |grep test

Myprocess  1234 user   12u     REG                1,4     100000         1234567 /Users/user/Folder/test.csv

Would show you if any file with the word test is being used and by what process.

This page has lots of useful examples of lsof:

http://www.thegeekstuff.com/2012/08/lsof-command-examples/


As you've mentioned, system can be used to call console commands such as lsof directly from R:

system('lsof')

You'll want to choose your directory/filename and then apply the appropriate logic as to whether the file is open:

try(amiopen <- system('lsof |grep test', intern=T))

if(is.na(amiopen[1])==T){print('Do some stuff with this file')}

To use a variable as the filename (as per this question):

myfile <- 'somefilename.txt'
try(amiopen <- system(sprintf("lsof |grep %s", myfile), intern=T))

Upvotes: 0

Related Questions