Guest User

Untitled

a guest
Aug 14th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. #import "FileSystemWatch.h"
  2.  
  3. #include <sys/event.h>
  4. #include <sys/time.h>
  5. #include <fcntl.h>
  6.  
  7.  
  8. @interface FileSystemWatch ()
  9. @property (nonatomic,retain) NSString* path;
  10. @property (nonatomic,assign) id target;
  11. @property (nonatomic,assign) SEL action;
  12. @property (nonatomic,assign) int fildes;
  13. @property (nonatomic,assign) int kq;
  14. @property (nonatomic,retain) NSThread* watchThread;
  15.  
  16. @end
  17.  
  18. @implementation FileSystemWatch
  19. @synthesize path = _path;
  20. @synthesize target = _target;
  21. @synthesize action = _action;
  22. @synthesize fildes = _fildes;
  23. @synthesize kq = _kq;
  24. @synthesize watchThread = _watchThread;
  25.  
  26. - (void)dealloc
  27. {
  28. [_path release], _path = nil;
  29. [_watchThread release], _watchThread = nil;
  30. [super dealloc];
  31. }
  32.  
  33. - (void)watchFileAtPath:(NSString*)path target:(id)target action:(SEL)action
  34. {
  35. self.path = path;
  36. self.target = target;
  37. self.action = action;
  38.  
  39. self.fildes = open([self.path UTF8String], O_RDONLY);
  40. if(self.fildes <= 0)
  41. {
  42. return;
  43. }
  44. self.kq = kqueue();
  45.  
  46. self.watchThread = [[[NSThread alloc] initWithTarget:self selector:@selector(watchInBackground) object:nil] autorelease];
  47. [self.watchThread start];
  48. }
  49.  
  50. - (void)stopWatching
  51. {
  52. close(self.kq);
  53. close(self.fildes);
  54. [self.watchThread cancel];
  55. }
  56.  
  57. - (void)watchInBackground
  58. {
  59. int status;
  60. struct kevent change;
  61. struct kevent event;
  62.  
  63. EV_SET(&change, self.fildes, EVFILT_VNODE,
  64. EV_ADD | EV_ENABLE | EV_ONESHOT,
  65. NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_ATTRIB,
  66. 0, 0);
  67.  
  68. while(status > 0)
  69. {
  70. status = kevent(self.kq, &change, 1, &event, 1, NULL);
  71.  
  72. if(status > 0)
  73. {
  74. if([self.target respondsToSelector:self.action])
  75. [self.target performSelectorOnMainThread:self.action withObject:self waitUntilDone:YES];
  76. }
  77. }
  78.  
  79. close(self.kq);
  80. close(self.fildes);
  81. }
  82.  
  83. @end
Add Comment
Please, Sign In to add comment