ADC Home > Reference Library > Reference > Darwin > File Management > FSEvents Reference

 


FSEvents.h

Includes:
<mach/mach.h>
<sys/types.h>
<CoreFoundation/CFRunLoop.h>
<CoreFoundation/CFUUID.h>
<AvailabilityMacros.h>

Overview



This header describes the FSEvents API. This API provides a mechanism to notify clients about directories they ought to re-scan in order to keep their internal data structures up-to-date with respect to the true state of the file system. (For example, when files or directories are created, modified, or removed.) It sends these notifications "in bulk", possibly notifying the client of changes to several directories in a single callback. By using the API, clients can notice such changes quickly, without needing to resort to recursive polling/scanning of the file system.

Much like kqueues, the FSEvents API allows an application to find near-immediately when the contents of a particular directory has changed. However, unlike kqueues, the FSEvents API allows the application to monitor the whole file system hierarchy rooted at a specified directory (and still get precise per-directory notifications) -- to do this with the kqueues API would require the client to monitor each directory individually.

Clients can register interest in a chunk of the filesystem hierarchy and will receive callbacks from their runloop whenever an event occurs that modifies the filesystem therein. The callback will indicate the exact directory in which the event occurred, so the client only has to scan that directory for updated info, not all its children. Clients can supply a "latency" parameter that tells how long to wait after an event occurs before forwarding it; this reduces the volume of events and reduces the chance that the client will see an "intermediate" state, like those that arise when doing a "safe save" of a file, creating a package, or downloading a file via Safari.



The lifecycle of an FSEventStream consists of these stages:

  1. FSEventStreamCreate() / FSEventStreamCreateRelativeToDevice() -> Creates an FSEventStream.

  2. FSEventStreamScheduleWithRunLoop() -> Schedules an FSEventStream on a runloop, like CFRunLoopAddSource() does for a CFRunLoopSourceRef.

  3. FSEventStreamStart() -> Starts receiving events and servicing them from the client's runloop(s) using the callback supplied by the client when the stream was created.

  4. FSEventStreamStop() -> Stops the stream, ensuring the client's callback will not be called again for this stream. After stopping the stream, it can be restarted via FSEventStreamStart().

  5. FSEventStreamInvalidate() -> Invalidates the stream, like CFRunLoopSourceInvalidate() does for a CFRunLoopSourcRef.

  6. FSEventStreamRelease() -> Decrements the refcount on the stream (initially one and incremented via FSEventStreamRetain()). If the refcount reaches zero, the stream is deallocated.
Once the event stream has been started, the following calls can be used:

FSEventStreamGetLatestEventId() -> Initially, this returns the sinceWhen value supplied when the stream was created; thereafter, it is updated with the highest-numbered event ID mentioned in the current batch of events just before invoking the client's callback. Clients can store this value persistently as long as they also store the UUID for the device (obtained via FSEventsCopyUUIDForDevice()). Clients can then later supply this event ID as the sinceWhen parameter to FSEventStreamCreateRelativeToDevice(), as long as its UUID matches what you stored. This works because the FSEvents service stores events in a persistent, per-volume database. In this regard,the stream of event IDs acts like a global, system-wide clock, but bears no relation to any particular timebase.

FSEventStreamFlushAsync() -> Requests that the fseventsd daemon send any events it has already buffered (via the latency parameter to one of the FSEventStreamCreate...() functions). This occurs asynchronously; clients will not have received all the callbacks by the time this call returns to them.

FSEventStreamFlushSync() -> Requests that the fseventsd daemon send any events it has already buffered (via the latency parameter to one of the FSEventStreamCreate...() functions). Then runs the runloop in its private mode till all events that have occurred have been reported (via the clients callback). This occurs synchronously; clients will have received all the callbacks by the time this call returns to them.

FSEventStreamGetDeviceBeingWatched() -> Gets the dev_t value supplied when the stream was created with FSEventStreamCreateRelativeToDevice(), otherwise 0.

FSEventStreamCopyPathsBeingWatched() -> Gets the paths supplied when the stream was created with one of the FSEventStreamCreate...() functions.

Calls that can be made without a stream:

FSEventsCopyUUIDForDevice() -> Gets a UUID that uniquely identifies the FSEvents database for that volume. If the database gets discarded then its replacement will have a different UUID so that clients will be able to detect this situation and avoid trying to use event IDs that they stored as the sinceWhen parameter to the FSEventStreamCreate...() functions.

FSEventsGetLastEventIdForDeviceBeforeTime() -> Gets the last event ID for the given device that was returned before the given time. This is conservative in the sense that if you then use the returned event ID as the sinceWhen parameter of FSEventStreamCreateRelativeToDevice() that you will not miss any events that happened since that time. On the other hand, you might receive some (harmless) extra events.

FSEventsPurgeEventsForDeviceUpToEventId() -> Purges old events from the persistent per-volume database maintained by the service. You can combine this with FSEventsGetLastEventIdForDeviceBeforeTime(). Can only be called by the root user.



Functions

FSEventsCopyUUIDForDevice
FSEventsGetCurrentEventId
FSEventsGetLastEventIdForDeviceBeforeTime
FSEventsPurgeEventsForDeviceUpToEventId
FSEventStreamCopyDescription
FSEventStreamCopyPathsBeingWatched
FSEventStreamCreate
FSEventStreamCreateRelativeToDevice
FSEventStreamFlushAsync
FSEventStreamFlushSync
FSEventStreamGetDeviceBeingWatched
FSEventStreamGetLatestEventId
FSEventStreamInvalidate
FSEventStreamRelease
FSEventStreamRetain
FSEventStreamScheduleWithRunLoop
FSEventStreamShow
FSEventStreamStart
FSEventStreamStop
FSEventStreamUnscheduleFromRunLoop

FSEventsCopyUUIDForDevice


CFUUIDRef FSEventsCopyUUIDForDevice(
    dev_t dev);  
Parameters
dev
The dev_t of the device that you want to get the UUID for.
Return Value

The UUID associated with the stream of events on this machine. Ownership follows the Copy Rule.

Discussion

Gets the UUID associated with a device. This uniquely identifies a given stream of FSEvents. If this UUID is different than one that you stored from a previous run then the event stream is different because it wrapped around back to zero or was purged (and thus any stored event IDs you may have are not valid).

Availability
Introduced in Mac OS X v10.5.

FSEventsGetCurrentEventId


FSEventStreamEventId FSEventsGetCurrentEventId(
    void);  
Return Value

The event ID of the most recent event generated by the system.

Discussion

Fetches the most current event ID on the system. The ID returned is for the most recently generated event and is therefore obsolete as soon as it is returned.

Availability
Introduced in Mac OS X v10.5.

FSEventsGetLastEventIdForDeviceBeforeTime


FSEventStreamEventId FSEventsGetLastEventIdForDeviceBeforeTime(
    dev_t dev,
    CFAbsoluteTime time);  
Parameters
dev
The dev_t of the device.
time
The time as a CFAbsoluteTime.
Return Value

The last event ID for the given device that was returned before the given time.

Discussion

Gets the last event ID for the given device that was returned before the given time. This is conservative in the sense that if you then use the returned event ID as the sinceWhen parameter of FSEventStreamCreateRelativeToDevice() that you will not miss any events that happened since that time. On the other hand, you might receive some (harmless) extra events.
Beware: there are things that can cause this to fail to be accurate. For example, someone might change the system's clock (either backwards or forwards). Or an external drive might be used on different systems without perfectly synchronized clocks.

Availability
Introduced in Mac OS X v10.5.

FSEventsPurgeEventsForDeviceUpToEventId


Boolean FSEventsPurgeEventsForDeviceUpToEventId(
    dev_t dev,
    FSEventStreamEventId eventId);  
Parameters
dev
The dev_t of the device.
eventId
The event ID.
Return Value

True if it succeeds, otherwise False if it fails.

Discussion

Purges old events from the persistent per-volume database maintained by the service. Can only be called by the root user.

Availability
Introduced in Mac OS X v10.5.

FSEventStreamCopyDescription


CFStringRef FSEventStreamCopyDescription( 
    ConstFSEventStreamRef streamRef);  
Return Value

A CFStringRef containing the description of the supplied stream. Ownership follows the Copy rule.

Discussion

Returns a CFStringRef containing the description of the supplied stream. For debugging only.

Availability
Introduced in Mac OS X v10.5.

FSEventStreamCopyPathsBeingWatched


CFArrayRef FSEventStreamCopyPathsBeingWatched( 
    ConstFSEventStreamRef streamRef);  
Parameters
streamRef
A valid stream.
Return Value

A CFArray of CFStringRefs corresponding to those supplied when the stream was created. Ownership follows the Copy rule.

Discussion

Fetches the paths supplied when the stream was created via one of the FSEventStreamCreate...() functions.

Availability
Introduced in Mac OS X v10.5.

FSEventStreamCreate


FSEventStreamRef FSEventStreamCreate( 
    CFAllocatorRef allocator, 
    FSEventStreamCallback callback, 
    FSEventStreamContext *context, 
    CFArrayRef pathsToWatch, 
    FSEventStreamEventId sinceWhen, 
    CFTimeInterval latency, 
    FSEventStreamCreateFlags flags);  
Parameters
allocator
The CFAllocator to be used to allocate memory for the stream. Pass NULL or kCFAllocatorDefault to use the current default allocator.
callback
An FSEventStreamCallback which will be called when FS events occur.
context
A pointer to the FSEventStreamContext structure the client wants to associate with this stream. Its fields are copied out into the stream itself so its memory can be released after the stream is created. Passing NULL is allowed and has the same effect as passing a structure whose fields are all set to zero.
pathsToWatch
A CFArray of CFStringRefs, each specifying a path to a directory, signifying the root of a filesystem hierarchy to be watched for modifications.
sinceWhen
The service will supply events that have happened after the given event ID. To ask for events "since now" pass the constant FSEventStreamEventIdSinceNow. Often, clients will supply the highest-numbered FSEventStreamEventId they have received in a callback, which they can obtain via the FSEventStreamGetLatestEventId() accessor. Do not pass zero for sinceWhen, unless you want to receive events for every directory modified since "the beginning of time" -- an unlikely scenario.
latency
The number of seconds the service should wait after hearing about an event from the kernel before passing it along to the client via its callback. Specifying a larger value may result in more effective temporal coalescing, resulting in fewer callbacks and greater overall efficiency.
flags
Specify kFSEventStreamCreateFlagNone to watch for events in the directory at the given path (and all its subdirectories, recursively).
Specify kFSEventStreamCreateFlagUseCFTypes to control what gets passed to the eventPaths argument of your callback. See the documentation for the callback function for more information.
The kFSEventStreamCreateFlagNoDefer flag controls the behavior of the latency parameter. If you specify the flag and more than latency seconds have elapsed since the last event, your app will receive the event immediately. The delivery of the event resets the latency timer and any further events will be delivered after latency seconds have elapsed. This flag is useful for apps that are interactive and want to react immediately to changes but avoid getting swamped by notifications when changes are occurring in rapid succession.
If you do not specify this flag, when an event occurs after a period of no events, the latency timer is started. Any events that occur during the next latency seconds will be delivered as one group (along with the first event). The delivery of the group of events resets the latency timer and any further events will be delivered after latency seconds. This is the default behavior and is appropriate for background, daemon or batch processing apps.
Return Value

A valid FSEventStreamRef.

Discussion

Creates a new FS event stream object with the given parameters. In order to start receiving callbacks you must also call FSEventStreamScheduleWithRunLoop() and FSEventStreamStart().

Availability
Introduced in Mac OS X v10.5.

FSEventStreamCreateRelativeToDevice


FSEventStreamRef FSEventStreamCreateRelativeToDevice( 
    CFAllocatorRef allocator, 
    FSEventStreamCallback callback, 
    FSEventStreamContext *context, 
    dev_t deviceToWatch, 
    CFArrayRef pathsToWatchRelativeToDevice, 
    FSEventStreamEventId sinceWhen, 
    CFTimeInterval latency, 
    FSEventStreamCreateFlags flags);  
Parameters
allocator
The CFAllocator to be used to allocate memory for the stream. Pass NULL or kCFAllocatorDefault to use the current default allocator.
callback
An FSEventStreamCallback which will be called when FS events occur.
context
A pointer to the FSEventStreamContext structure the client wants to associate with this stream. Its fields are copied out into the stream itself so its memory can be released after the stream is created.
deviceToWatch
A dev_t corresponding to the device which you want to receive notifications from. The dev_t is the same as the st_dev field from a stat structure of a file on that device or the f_fsid[0] field of a statfs structure. If the value of dev is zero, it is ignored.
pathsToWatchRelativeToDevice
A CFArray of CFStringRefs, each specifying a relative path to a directory on the device identified by the dev parameter. The paths should be relative to the root of the device. For example, if a volume "MyData" is mounted at "/Volumes/MyData" and you want to watch "/Volumes/MyData/Pictures/July", specify a path string of "Pictures/July". To watch the root of a volume pass a path of "" (the empty string).
sinceWhen
The service will supply events that have happened after the given event ID. To ask for events "since now" pass the constant FSEventStreamEventIdSinceNow. Often, clients will supply the highest-numbered FSEventStreamEventId they have received in a callback, which they can obtain via the FSEventStreamGetLatestEventId() accessor. Do not pass zero for sinceWhen, unless you want to receive events for every directory modified since "the beginning of time" -- an unlikely scenario.
latency
The number of seconds the service should wait after hearing about an event from the kernel before passing it along to the client via its callback. Specifying a larger value may result in more effective temporal coalescing, resulting in fewer callbacks.
flags
Specify kFSEventStreamCreateFlagNone to watch for events in the directory at the given path (and all its subdirectories, recursively).
Return Value

A valid FSEventStreamRef.

Discussion

Creates a new FS event stream object for a particular device with the given parameters. In order to start receiving callbacks you must also call FSEventStreamScheduleWithRunLoop() and FSEventStreamStart().

Availability
Introduced in Mac OS X v10.5.

FSEventStreamFlushAsync


void FSEventStreamFlushAsync( 
    FSEventStreamRef streamRef);  
Parameters
streamRef
A valid stream.
Discussion

Asks the FS Events service to flush out any events that have occurred but have not yet been delivered, due to the latency parameter that was supplied when the stream was created. This flushing occurs asynchronously -- do not expect the events to have already been delivered by the time this call returns.
FSEventStreamFlushAsync() can only be called after the stream has been started, via FSEventStreamStart().

Availability
Introduced in Mac OS X v10.5.

FSEventStreamFlushSync


void FSEventStreamFlushSync( 
    FSEventStreamRef streamRef);  
Parameters
streamRef
A valid stream.
Discussion

Asks the FS Events service to flush out any events that have occurred but have not yet been delivered, due to the latency parameter that was supplied when the stream was created. This flushing occurs synchronously -- by the time this call returns, your callback will have been invoked for every event that had already occurred at the time you made this call.
FSEventStreamFlushSync() can only be called after the stream has been started, via FSEventStreamStart().

Availability
Introduced in Mac OS X v10.5.

FSEventStreamGetDeviceBeingWatched


dev_t FSEventStreamGetDeviceBeingWatched( 
    ConstFSEventStreamRef streamRef);  
Parameters
streamRef
A valid stream.
Return Value

The dev_t for a device-relative stream, otherwise 0.

Discussion

Fetches the dev_t supplied when the stream was created via FSEventStreamCreateRelativeToDevice(), otherwise 0.

Availability
Introduced in Mac OS X v10.5.

FSEventStreamGetLatestEventId


FSEventStreamEventId FSEventStreamGetLatestEventId( 
    ConstFSEventStreamRef streamRef);  
Parameters
streamRef
A valid stream.
Return Value

The sinceWhen attribute of the stream.

Discussion

Fetches the sinceWhen property of the stream. Upon receiving an event (and just before invoking the client's callback) this attribute is updated to the highest-numbered event ID mentioned in the event.

Availability
Introduced in Mac OS X v10.5.

FSEventStreamInvalidate


void FSEventStreamInvalidate( 
    FSEventStreamRef streamRef);  
Parameters
streamRef
A valid stream.
Discussion

Invalidates the stream, like CFRunLoopSourceInvalidate() does for a CFRunLoopSourceRef. It will be unscheduled from any runloops upon which it had been scheduled.
FSEventStreamInvalidate() can only be called after the stream has been scheduled on at least one runloop, via FSEventStreamSchedueWithRunLoop().

Availability
Introduced in Mac OS X v10.5.

FSEventStreamRelease


void FSEventStreamRelease( 
    FSEventStreamRef streamRef);  
Parameters
streamRef
A valid stream.
Discussion

Decrements the stream's refcount. The refcount is initially one and is incremented via FSEventStreamRetain(). If the refcount reaches zero then the stream is deallocated.

Availability
Introduced in Mac OS X v10.5.

FSEventStreamRetain


void FSEventStreamRetain( 
    FSEventStreamRef streamRef);  
Parameters
streamRef
A valid stream.
Discussion

Increments the stream's refcount. The refcount is initially one and is decremented via FSEventStreamRelease().

Availability
Introduced in Mac OS X v10.5.

FSEventStreamScheduleWithRunLoop


void FSEventStreamScheduleWithRunLoop( 
    FSEventStreamRef streamRef, 
    CFRunLoopRef runLoop, 
    CFStringRef runLoopMode);  
Parameters
streamRef
A valid stream.
runLoop
The run loop on which to schedule the stream.
runLoopMode
A run loop mode on which to schedule the stream.
Discussion

This function schedules the stream on the specified run loop, like CFRunLoopAddSource() does for a CFRunLoopSourceRef. The caller is responsible for ensuring that the stream is scheduled on at least one run loop and that at least one of the run loops on which the stream is scheduled is being run.
To start receiving events on the stream, call FSEventStreamStart().
To remove the stream from the run loops upon which it has been scheduled, call FSEventStreamUnscheduleFromRunLoop() or FSEventStreamInvalidate().

Availability
Introduced in Mac OS X v10.5.

FSEventStreamShow


void FSEventStreamShow( 
    ConstFSEventStreamRef streamRef);  
Parameters
streamRef
A valid stream.
Discussion

Prints a description of the supplied stream to stderr. For debugging only.

Availability
Introduced in Mac OS X v10.5.

FSEventStreamStart


Boolean FSEventStreamStart( 
    FSEventStreamRef streamRef);  
Parameters
streamRef
A valid stream.
Return Value

True if it succeeds, otherwise False if it fails. It ought to always succeed, but in the event it does not then your code should fall back to performing recursive scans of the directories of interest as appropriate.

Discussion

Attempts to register with the FS Events service to receive events per the parameters in the stream.
FSEventStreamStart() can only be called once the stream has been scheduled on at least one runloop, via FSEventStreamScheduleWithRunLoop().
Once started, the stream can be stopped via FSEventStreamStop().

Availability
Introduced in Mac OS X v10.5.

FSEventStreamStop


void FSEventStreamStop( 
    FSEventStreamRef streamRef);  
Parameters
streamRef
A valid stream.
Discussion

Unregisters with the FS Events service. The client callback will not be called for this stream while it is stopped.
FSEventStreamStop() can only be called if the stream has been started, via FSEventStreamStart().
Once stopped, the stream can be restarted via FSEventStreamStart(), at which point it will resume receiving events from where it left off ("sinceWhen").

Availability
Introduced in Mac OS X v10.5.

FSEventStreamUnscheduleFromRunLoop


void FSEventStreamUnscheduleFromRunLoop( 
    FSEventStreamRef streamRef, 
    CFRunLoopRef runLoop, 
    CFStringRef runLoopMode);  
Parameters
streamRef
A valid stream.
runLoop
The run loop from which to unschedule the stream.
runLoopMode
The run loop mode from which to unschedule the stream.
Discussion

This function removes the stream from the specified run loop, like CFRunLoopRemoveSource() does for a CFRunLoopSourceRef.

Availability
Introduced in Mac OS X v10.5.

Typedefs


ConstFSEventStreamRef


typedef const struct __FSEventStream *ConstFSEventStreamRef;  
Discussion

This is the type of a reference to a constant FSEventStream.


FSEventStreamCallback


typedef void ( *FSEventStreamCallback)( 
    ConstFSEventStreamRef streamRef, 
    void *clientCallBackInfo, 
    size_t numEvents, 
    void *eventPaths, 
    const FSEventStreamEventFlags eventFlags[], 
    const FSEventStreamEventId eventIds[]);  
Discussion

This is the type of the callback function supplied by the client when creating a new stream. This callback is invoked by the service from the client's runloop(s) when events occur, per the parameters specified when the stream was created.


FSEventStreamContext


typedef struct FSEventStreamContext { 
    CFIndex version; 
    void *info; 
    CFAllocatorRetainCallBack retain; 
    CFAllocatorReleaseCallBack release; 
    CFAllocatorCopyDescriptionCallBack copyDescription; 
} FSEventStreamContext;  
Fields
version
Currently the only valid value is zero.
info
An arbitrary client-defined value (for instance, a pointer) to be associated with the stream and passed to the callback when it is invoked. If a non-NULL value is supplied for the retain callback the framework will use it to retain this value. If a non-NULL value is supplied for the release callback then when the stream is deallocated it will be used to release this value. This can be NULL.
retain
The callback used retain the info pointer. This can be NULL.
release
The callback used release a retain on the info pointer. This can be NULL.
copyDescription
The callback used to create a descriptive string representation of the info pointer (or the data pointed to by the info pointer) for debugging purposes. This can be NULL.
Discussion

Structure containing client-supplied data (and callbacks to manage it) that should be associated with a newly-created stream.


FSEventStreamCreateFlags


typedef UInt32 FSEventStreamCreateFlags;  
Discussion

Flags that can be passed to the FSEventStreamCreate...() functions.


FSEventStreamEventFlags


typedef UInt32 FSEventStreamEventFlags;  
Discussion

Flags that can be passed to FSEventStreamCallback().


FSEventStreamEventId


typedef uint64_t FSEventStreamEventId;  
Discussion

Event IDs that can be passed to the FSEventStreamCreate...() functions and FSEventStreamCallback(). They are monotonically increasing per system, even across reboots and drives coming and going. They bear no relation to any particular clock or timebase.


FSEventStreamRef


typedef struct __FSEventStream *FSEventStreamRef;  
Discussion

This is the type of a reference to an FSEventStream.


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.
Last Updated: 2008-03-11