Jon W
Jon W

Reputation: 35

NSPipe input from process I don't control

I have an application written in Objective-C and am trying to receive messages from an app written in C. It appears I have two options... XPC services and Piping. In regards to NSPipe - I am trying to determine how I can open a pipe that watches a file at a given location for new data. Simply put, I need to know when new data is written to file at path XYZ. However all of the examples I find with NSPipe seems to be among tasks that communicate with each other, and all of these tasks are spawned and owned by the same central app... so they never specify a file to watch. They instead just assign the inputs of one process as the outputs of another. Since I don't own the C based application, I cannot just assign the output of that C program as the input of a task that I own. Instead, I am expecting data to be written to a file, and need to know when it arrives. How can I achieve this?

Upvotes: 0

Views: 121

Answers (1)

R.Srinath
R.Srinath

Reputation: 21

I am not sure from where i got this code , but i am pretty sure i copied this code from somewhere in stackoverflow only. This code monitors the file and executes the statements inside the if() condition when the file it is watching has changed.

-(void)monitorFile:(NSString*) path   
{

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
int fildes = open([path UTF8String], O_EVTONLY);

__block typeof(self) blockSelf = self;
__block dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, fildes,
                                                          DISPATCH_VNODE_DELETE | DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND |
                                                          DISPATCH_VNODE_ATTRIB | DISPATCH_VNODE_LINK | DISPATCH_VNODE_RENAME |
                                                          DISPATCH_VNODE_REVOKE, queue);
dispatch_source_set_event_handler(source, ^{
    unsigned long flags = dispatch_source_get_data(source);
    if(flags) 
    {
        // Do Stuff here
        [blockSelf monitorFile:path];
    }
});
dispatch_source_set_cancel_handler(source, ^(void) {
    close(fildes);
});
dispatch_resume(source);
}

Edit: i found the original answer from which i copied from : https://stackoverflow.com/a/26304208/7433869

Upvotes: 0

Related Questions