How to check if a file is open or not using Cocoa/Objective-C?

First let me make it clear that we are not discussing about finding if a application is running or not, which can be found out very easily by using  [[NSWorkspace sharedWorkspace]  runningApplications].

We are going to discuss how if we can, get the information about a file that whether it is open or not through a Cocoa Application.

Before going further down in the topic let us consider following scenarios to understand the need of the discussion.

1. A Cocoa application might be concerned with performance enhancement and for that it might need to find and list out the opened files.

2. A application might need to find the port associated with a daemon.

3. A application might need to constantly monitor a document or documents in a particular directory and when user close that document after editing, it has to perform certain tasks.

So, let’s start our search to find a Cocoa API which can accomplish this. Unfortunately there is none…

Let’s see if we can use apple script to get this information. Again, apple script also does not provide any workaround.

Ok, we have failed so far. Let’s explore Unix commands..

Voila…. there is a Unix command which we can use lsof (list open files).

Examples : (from Wikipedia)

# lsof /var
COMMAND          PID    USER    FD     TYPE     DEVICE     SIZE/OFF     NODE      NAME
syslogd                    350    root       5w      VREG     222,5          0                       440818   /var/adm/messages
syslogd                    350    root       6w      VREG     222,5          339098         6248        /var/log/syslog
cron                          353    root        cwd    VDIR      222,5          512                  254550   /var — atjobs

# lsof -i -n -P | grep sendmail
sendmail                 31649  root      4u        IPv4       521738     TCP *:25 (LISTEN)

We will use this command to accomplish our task.
Now we have two options. One is that we make a shell script and invoke that script from our application, Second is to directly run this command from the Cocoa application.

We will use the second option and thus in process will show how to execute the Unix command from Cocoa application using Objective-C.

Following is the Objective-C code for accomplishing the desired task.

-(NSString *)checkStatusOfFile:(NSString *)fileName inDirectory:(NSString *)directory


//The function checks whether the document “fileName” is open or not.

//NSTask is used to run the terminal command from a the cocoa application

NSTask *task;

task = [[NSTask alloc] init];

//Set the path at which document is present

[task setCurrentDirectoryPath: directory];

//Set terminal command which has to be run for determining whether the document is open or not

[task setLaunchPath:@”/usr/sbin/lsof”];

//Set the name of the document

NSArray *arguments;

arguments = [NSArray arrayWithObjects:fileName,nil];

[task setArguments: arguments];

NSPipe *pipe;

pipe = [NSPipe pipe];

[task setStandardOutput: pipe];

NSFileHandle *file;

file = [pipe fileHandleForReading];

[task launch];

NSData *data;

data = [file readDataToEndOfFile];

NSString *string;

string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];

NSLog (@”result:\n%@”, string);

[task release];

return [string autorelease];


I ran the code for “animation.doc” on my desktop and following is the log when it was open with NeoOffice. When animation.doc was closed the log was empty.

Note : The code didn’t worked for documents opened in TextEdit.


soffice.b           1748   hem       56u   REG      14,2            1341440       8185461 animation.doc
mdworker3     4139  hem       6r       REG     14,2            1341440       8185461 animation.doc


Written By: HEM DUTT, Sr. Engineer/Tech Lead (Mac OSX development), Mindfire Solutions



Seasoned Mac OS X developer. Expertise in Mac OSX application development. knowledge of MFC and IOS

Posted on January 27, 2014, in Cocoa Application, Objective-C, Unix Commands and tagged , , , , , , . Bookmark the permalink. 2 Comments.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: