本文整理匯總了C++中CFRunLoopAddSource函數的典型用法代碼示例。如果您正苦於以下問題:C++ CFRunLoopAddSource函數的具體用法?C++ CFRunLoopAddSource怎麽用?C++ CFRunLoopAddSource使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了CFRunLoopAddSource函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C++代碼示例。
示例1: initializeDisplayNotifications
static void initializeDisplayNotifications (void)
{
io_service_t displayWrangler;
IONotificationPortRef notificationPort;
io_object_t notifier;
displayWrangler = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching("IODisplayWrangler"));
if (! displayWrangler) {
message (LOG_ERR, "IOServiceGetMatchingService failed\n");
exit (1);
}
notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
if (! notificationPort) {
message (LOG_ERR, "IONotificationPortCreate failed\n");
exit (1);
}
if (IOServiceAddInterestNotification(notificationPort, displayWrangler, kIOGeneralInterest,
displayCallback, NULL, ¬ifier) != kIOReturnSuccess) {
message (LOG_ERR, "IOServiceAddInterestNotification failed\n");
exit (1);
}
CFRunLoopAddSource (CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPort), kCFRunLoopDefaultMode);
IOObjectRelease (displayWrangler);
}
示例2: m_isOnLine
NetworkStateNotifier::NetworkStateNotifier()
: m_isOnLine(false)
, m_networkStateChangedFunction(0)
, m_networkStateChangeTimer(this, &NetworkStateNotifier::networkStateChangeTimerFired)
{
SCDynamicStoreContext context = { 0, this, 0, 0, 0 };
m_store.adoptCF(SCDynamicStoreCreate(0, CFSTR("com.apple.WebCore"), dynamicStoreCallback, &context));
if (!m_store)
return;
RetainPtr<CFRunLoopSourceRef> configSource = SCDynamicStoreCreateRunLoopSource(0, m_store.get(), 0);
if (!configSource)
return;
CFRunLoopAddSource(CFRunLoopGetMain(), configSource.get(), kCFRunLoopCommonModes);
RetainPtr<CFMutableArrayRef> keys(AdoptCF, CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));
RetainPtr<CFMutableArrayRef> patterns(AdoptCF, CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks));
RetainPtr<CFStringRef> key;
RetainPtr<CFStringRef> pattern;
key.adoptCF(SCDynamicStoreKeyCreateNetworkGlobalEntity(0, kSCDynamicStoreDomainState, kSCEntNetIPv4));
CFArrayAppendValue(keys.get(), key.get());
pattern.adoptCF(SCDynamicStoreKeyCreateNetworkInterfaceEntity(0, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4));
CFArrayAppendValue(patterns.get(), pattern.get());
key.adoptCF(SCDynamicStoreKeyCreateNetworkGlobalEntity(0, kSCDynamicStoreDomainState, kSCEntNetDNS));
CFArrayAppendValue(keys.get(), key.get());
SCDynamicStoreSetNotificationKeys(m_store.get(), keys.get(), patterns.get());
updateState();
}
示例3: MyDNSServiceAddToRunLoop
static void
MyDNSServiceAddToRunLoop(MyDNSServiceState *ref)
{
CFSocketNativeHandle sock;
CFOptionFlags sockFlags;
CFRunLoopSourceRef source;
CFSocketContext context = { 0, ref, NULL, NULL, NULL }; // Use MyDNSServiceState as context data.
assert(ref);
// Access the underlying Unix domain socket to communicate with the mDNSResponder daemon.
sock = DNSServiceRefSockFD(ref->service);
assert(sock >= 0);
// Create a CFSocket using the Unix domain socket.
ref->socket = CFSocketCreateWithNative(NULL, sock, kCFSocketReadCallBack, MyDNSServiceSocketCallBack, &context);
assert(ref->socket);
// Prevent CFSocketInvalidate from closing DNSServiceRef's socket.
sockFlags = CFSocketGetSocketFlags(ref->socket);
CFSocketSetSocketFlags(ref->socket, sockFlags & (~kCFSocketCloseOnInvalidate));
// Create a CFRunLoopSource from the CFSocket.
source = CFSocketCreateRunLoopSource(NULL, ref->socket, 0);
assert(source);
// Add the CFRunLoopSource to the current runloop.
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes);
// We no longer need our reference to source. The runloop continues to
// hold a reference to it, but we don't care about that. When we invalidate
// the socket, the runloop will drop its reference and the source will get
// destroyed.
CFRelease(source);
}
示例4: watchQuietEnable
static void
watchQuietEnable()
{
CFArrayRef keys;
Boolean ok;
initKey = SCDynamicStoreKeyCreate(NULL,
CFSTR("%@" "InterfaceNamer"),
kSCDynamicStoreDomainPlugin);
initRls = SCDynamicStoreCreateRunLoopSource(NULL, store, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), initRls, kCFRunLoopDefaultMode);
keys = CFArrayCreate(NULL, (const void **)&initKey, 1, &kCFTypeArrayCallBacks);
ok = SCDynamicStoreSetNotificationKeys(store, keys, NULL);
CFRelease(keys);
if (!ok) {
SCLog(TRUE, LOG_ERR,
CFSTR("SCDynamicStoreSetNotificationKeys() failed: %s\n"), SCErrorString(SCError()));
watchQuietDisable();
}
return;
}
示例5: IOHIDDeviceScheduleWithRunLoop
static void *read_thread(void *param)
{
hid_device *dev = param;
/* Move the device's run loop to this thread. */
IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetCurrent(), dev->run_loop_mode);
/* Create the RunLoopSource which is used to signal the
event loop to stop when hid_close() is called. */
CFRunLoopSourceContext ctx;
memset(&ctx, 0, sizeof(ctx));
ctx.version = 0;
ctx.info = dev;
ctx.perform = &perform_signal_callback;
dev->source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0/*order*/, &ctx);
CFRunLoopAddSource(CFRunLoopGetCurrent(), dev->source, dev->run_loop_mode);
/* Store off the Run Loop so it can be stopped from hid_close()
and on device disconnection. */
dev->run_loop = CFRunLoopGetCurrent();
/* Notify the main thread that the read thread is up and running. */
pthread_barrier_wait(&dev->barrier);
/* Run the Event Loop. CFRunLoopRunInMode() will dispatch HID input
reports into the hid_report_callback(). */
SInt32 code;
while (!dev->shutdown_thread && !dev->disconnected) {
code = CFRunLoopRunInMode(dev->run_loop_mode, 1000/*sec*/, FALSE);
/* Return if the device has been disconnected */
if (code == kCFRunLoopRunFinished) {
dev->disconnected = 1;
break;
}
/* Break if The Run Loop returns Finished or Stopped. */
if (code != kCFRunLoopRunTimedOut &&
code != kCFRunLoopRunHandledSource) {
/* There was some kind of error. Setting
shutdown seems to make sense, but
there may be something else more appropriate */
dev->shutdown_thread = 1;
break;
}
}
/* Now that the read thread is stopping, Wake any threads which are
waiting on data (in hid_read_timeout()). Do this under a mutex to
make sure that a thread which is about to go to sleep waiting on
the condition acutally will go to sleep before the condition is
signaled. */
pthread_mutex_lock(&dev->mutex);
pthread_cond_broadcast(&dev->condition);
pthread_mutex_unlock(&dev->mutex);
/* Close the OS handle to the device, but only if it's not
been unplugged. If it's been unplugged, then calling
IOHIDDeviceClose() will crash. */
if (!dev->disconnected) {
IOHIDDeviceClose(dev->device_handle, kIOHIDOptionsTypeNone);
}
/* Wait here until hid_close() is called and makes it past
the call to CFRunLoopWakeUp(). This thread still needs to
be valid when that function is called on the other thread. */
pthread_barrier_wait(&dev->shutdown_barrier);
return NULL;
}
示例6: ConnectionRegisterListener
static int ConnectionRegisterListener(
ConnectionRef conn,
CFRunLoopRef runLoop,
CFStringRef runLoopMode,
ConnectionCallbackProcPtr callback,
void * refCon
)
// Register a listener to be called when packets arrive. Once you've done
// this, you can no longer use conn for RPCs.
//
// conn must be a valid connection
//
// runLoop and runLoopMode specify the context in which the callback will
// be called; in most cases you specify CFRunLoopGetCurrent() and
// kCFRunLoopDefaultMode
//
// callback is the function you want to be called when packets arrive; it
// must not be NULL
//
// refCon is passed to callback
//
// Returns an errno-style error code
// On success, the connection has been converted to a listener and your
// callback will be called from the context of the specific runloop when
// a packet arrives; on error, the connection is no longer useful (conn is
// still valid, but you can't use it to transmit any more data)
{
int err;
assert(conn != NULL);
assert(runLoop != NULL);
assert(runLoopMode != NULL);
assert(callback != NULL);
assert(conn->fSockFD != -1); // connection must not be shut down
assert(conn->fSockCF == NULL); // can't register twice
// Create the packet buffer.
err = 0;
conn->fBufferedPackets = CFDataCreateMutable(NULL, 0);
if (conn->fBufferedPackets == NULL) {
err = ENOMEM;
}
// Add the source to the runloop.
if (err == 0) {
CFSocketContext context;
memset(&context, 0, sizeof(context));
context.info = conn;
conn->fSockCF = CFSocketCreateWithNative(
NULL,
(CFSocketNativeHandle) conn->fSockFD,
kCFSocketDataCallBack,
ConnectionGotData,
&context
);
if (conn->fSockCF == NULL) {
err = EINVAL;
}
}
if (err == 0) {
conn->fRunLoopSource = CFSocketCreateRunLoopSource(NULL, conn->fSockCF, 0);
if (conn->fRunLoopSource == NULL) {
err = EINVAL;
}
}
if (err == 0) {
conn->fCallback = callback;
conn->fCallbackRefCon = refCon;
CFRunLoopAddSource( runLoop, conn->fRunLoopSource, runLoopMode);
}
// Any failure means the entire connection is dead; again, this is the
// draconian approach to error handling. But hey, connections are
// (relatively) cheap.
if (err != 0) {
ConnectionShutdown(conn);
}
return err;
}
示例7: UPSDeviceAdded
void UPSDeviceAdded(void *refCon, io_iterator_t iterator)
{
io_object_t upsDevice = MACH_PORT_NULL;
UPSDataRef upsDataRef = NULL;
CFDictionaryRef upsProperties = NULL;
CFDictionaryRef upsEvent = NULL;
CFSetRef upsCapabilites = NULL;
CFRunLoopSourceRef upsEventSource = NULL;
CFRunLoopTimerRef upsEventTimer = NULL;
CFTypeRef typeRef = NULL;
IOCFPlugInInterface ** plugInInterface = NULL;
IOUPSPlugInInterface_v140 ** upsPlugInInterface = NULL;
HRESULT result = S_FALSE;
IOReturn kr;
SInt32 score;
while ( (upsDevice = IOIteratorNext(iterator)) )
{
// Create the CF plugin for this device
kr = IOCreatePlugInInterfaceForService(upsDevice, kIOUPSPlugInTypeID,
kIOCFPlugInInterfaceID, &plugInInterface, &score);
if ( kr != kIOReturnSuccess )
goto UPSDEVICEADDED_NONPLUGIN_CLEANUP;
// Grab the new v140 interface
result = (*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOUPSPlugInInterfaceID_v140),
(LPVOID)&upsPlugInInterface);
if ( ( result == S_OK ) && upsPlugInInterface )
{
kr = (*upsPlugInInterface)->createAsyncEventSource(upsPlugInInterface, &typeRef);
if ((kr != kIOReturnSuccess) || !typeRef)
goto UPSDEVICEADDED_FAIL;
if ( CFGetTypeID(typeRef) == CFRunLoopTimerGetTypeID() )
{
upsEventTimer = (CFRunLoopTimerRef)typeRef;
CFRunLoopAddTimer(CFRunLoopGetCurrent(), upsEventTimer, kCFRunLoopDefaultMode);
}
else if ( CFGetTypeID(typeRef) == CFRunLoopSourceGetTypeID() )
{
upsEventSource = (CFRunLoopSourceRef)typeRef;
CFRunLoopAddSource(CFRunLoopGetCurrent(), upsEventSource, kCFRunLoopDefaultMode);
}
}
// Couldn't grab the new interface. Fallback on the old.
else
{
result = (*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOUPSPlugInInterfaceID),
(LPVOID)&upsPlugInInterface);
}
// Got the interface
if ( ( result == S_OK ) && upsPlugInInterface )
{
kr = (*upsPlugInInterface)->getProperties(upsPlugInInterface, &upsProperties);
if (kr != kIOReturnSuccess)
goto UPSDEVICEADDED_FAIL;
upsDataRef = GetPrivateData(upsProperties);
if ( !upsDataRef )
goto UPSDEVICEADDED_FAIL;
upsDataRef->upsPlugInInterface = (IOUPSPlugInInterface **)upsPlugInInterface;
upsDataRef->upsEventSource = upsEventSource;
upsDataRef->upsEventTimer = upsEventTimer;
upsDataRef->isPresent = true;
kr = (*upsPlugInInterface)->getCapabilities(upsPlugInInterface, &upsCapabilites);
if (kr != kIOReturnSuccess)
goto UPSDEVICEADDED_FAIL;
kr = CreatePowerManagerUPSEntry(upsDataRef, upsProperties, upsCapabilites);
if (kr != kIOReturnSuccess)
goto UPSDEVICEADDED_FAIL;
kr = (*upsPlugInInterface)->getEvent(upsPlugInInterface, &upsEvent);
if (kr != kIOReturnSuccess)
goto UPSDEVICEADDED_FAIL;
ProcessUPSEvent(upsDataRef, upsEvent);
(*upsPlugInInterface)->setEventCallback(upsPlugInInterface, UPSEventCallback, NULL, upsDataRef);
IOServiceAddInterestNotification(
gNotifyPort, // notifyPort
upsDevice, // service
kIOGeneralInterest, // interestType
DeviceNotification, // callback
upsDataRef, // refCon
&(upsDataRef->notification) // notification
);
//.........這裏部分代碼省略.........
示例8: CreateIPAddressListChangeCallbackSCF
static OSStatus
CreateIPAddressListChangeCallbackSCF(SCDynamicStoreCallBack callback,
void *contextPtr,
SCDynamicStoreRef *storeRef,
CFRunLoopSourceRef *sourceRef)
// Create a SCF dynamic store reference and a
// corresponding CFRunLoop source. If you add the
// run loop source to your run loop then the supplied
// callback function will be called when local IP
// address list changes.
{
OSStatus err = 0;
SCDynamicStoreContext context = {0, NULL, NULL, NULL, NULL};
SCDynamicStoreRef ref;
CFStringRef pattern;
CFArrayRef patternList;
CFRunLoopSourceRef rls;
assert(callback != NULL);
assert( storeRef != NULL);
assert(*storeRef == NULL);
assert( sourceRef != NULL);
assert(*sourceRef == NULL);
ref = NULL;
pattern = NULL;
patternList = NULL;
rls = NULL;
// Create a connection to the dynamic store, then create
// a search pattern that finds all IPv4 entities.
// The pattern is "State:/Network/Service/[^/]+/IPv4".
context.info = contextPtr;
ref = SCDynamicStoreCreate( NULL,
CFSTR("AddIPAddressListChangeCallbackSCF"),
callback,
&context);
//err = MoreSCError(ref);
if (err == noErr) {
pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(
NULL,
kSCDynamicStoreDomainState,
kSCCompAnyRegex,
kSCEntNetIPv4);
//err = MoreSCError(pattern);
}
// Create a pattern list containing just one pattern,
// then tell SCF that we want to watch changes in keys
// that match that pattern list, then create our run loop
// source.
if (err == noErr) {
patternList = CFArrayCreate(NULL,
(const void **) &pattern, 1,
&kCFTypeArrayCallBacks);
//err = CFQError(patternList);
}
if (err == noErr) {
//err = MoreSCErrorBoolean(
SCDynamicStoreSetNotificationKeys(
ref,
NULL,
patternList);
// );
}
if (err == noErr) {
rls = SCDynamicStoreCreateRunLoopSource(NULL, ref, 0);
//err = MoreSCError(rls);
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), rls,
kCFRunLoopDefaultMode);
// Clean up.
//CFQRelease(pattern);
//CFQRelease(patternList);
if (err != noErr) {
//CFQRelease(ref);
ref = NULL;
}
*storeRef = ref;
*sourceRef = rls;
assert( (err == noErr) == (*storeRef != NULL) );
assert( (err == noErr) == (*sourceRef != NULL) );
return err;
}
示例9: darwinHIDKeyboardCacheCreateEntry
/**
* Creates a keyboard cache entry.
*
* @returns true if the entry was created successfully, otherwise false.
* @param pKeyboardEntry Pointer to the entry.
* @param KeyboardDevice The keyboard device to create the entry for.
*
*/
static bool darwinHIDKeyboardCacheCreateEntry(struct KeyboardCacheData *pKeyboardEntry, io_object_t KeyboardDevice)
{
unsigned long cRefs = 0;
memset(pKeyboardEntry, 0, sizeof(*pKeyboardEntry));
/*
* Query the HIDDeviceInterface for this HID (keyboard) object.
*/
SInt32 Score = 0;
IOCFPlugInInterface **ppPlugInInterface = NULL;
IOReturn rc = IOCreatePlugInInterfaceForService(KeyboardDevice, kIOHIDDeviceUserClientTypeID,
kIOCFPlugInInterfaceID, &ppPlugInInterface, &Score);
if (rc == kIOReturnSuccess)
{
IOHIDDeviceInterface **ppHidDeviceInterface = NULL;
HRESULT hrc = (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID),
(LPVOID *)&ppHidDeviceInterface);
cRefs = (*ppPlugInInterface)->Release(ppPlugInInterface); MY_CHECK_CREFS(cRefs);
ppPlugInInterface = NULL;
if (hrc == S_OK)
{
rc = (*ppHidDeviceInterface)->open(ppHidDeviceInterface, 0);
if (rc == kIOReturnSuccess)
{
/*
* create a removal callback.
*/
/** @todo */
/*
* Create the queue so we can insert elements while searching the properties.
*/
IOHIDQueueInterface **ppHidQueueInterface = (*ppHidDeviceInterface)->allocQueue(ppHidDeviceInterface);
if (ppHidQueueInterface)
{
rc = (*ppHidQueueInterface)->create(ppHidQueueInterface, 0, 32);
if (rc != kIOReturnSuccess)
{
AssertMsgFailed(("rc=%d\n", rc));
cRefs = (*ppHidQueueInterface)->Release(ppHidQueueInterface); MY_CHECK_CREFS(cRefs);
ppHidQueueInterface = NULL;
}
}
else
AssertFailed();
pKeyboardEntry->ppHidQueueInterface = ppHidQueueInterface;
/*
* Brute force getting of attributes.
*/
/** @todo read up on how to do this in a less resource intensive way! Suggestions are welcome! */
CFMutableDictionaryRef PropertiesRef = 0;
kern_return_t krc = IORegistryEntryCreateCFProperties(KeyboardDevice, &PropertiesRef, kCFAllocatorDefault, kNilOptions);
if (krc == KERN_SUCCESS)
{
darwinBruteForcePropertySearch(PropertiesRef, pKeyboardEntry);
CFRelease(PropertiesRef);
}
else
AssertMsgFailed(("krc=%#x\n", krc));
if (ppHidQueueInterface)
{
/*
* Now install our queue callback.
*/
CFRunLoopSourceRef RunLoopSrcRef = NULL;
rc = (*ppHidQueueInterface)->createAsyncEventSource(ppHidQueueInterface, &RunLoopSrcRef);
if (rc == kIOReturnSuccess)
{
CFRunLoopRef RunLoopRef = (CFRunLoopRef)GetCFRunLoopFromEventLoop(GetMainEventLoop());
CFRunLoopAddSource(RunLoopRef, RunLoopSrcRef, kCFRunLoopDefaultMode);
}
/*
* Now install our queue callback.
*/
rc = (*ppHidQueueInterface)->setEventCallout(ppHidQueueInterface, darwinQueueCallback, ppHidQueueInterface, pKeyboardEntry);
if (rc != kIOReturnSuccess)
AssertMsgFailed(("rc=%d\n", rc));
}
/*
* Complete the new keyboard cache entry.
*/
pKeyboardEntry->ppHidDeviceInterface = ppHidDeviceInterface;
pKeyboardEntry->ppHidQueueInterface = ppHidQueueInterface;
return true;
}
//.........這裏部分代碼省略.........
示例10: main
int main(int argc, const char *argv[])
{
time_t current_time = time(NULL);
char* c_time_string = ctime(¤t_time);
size_t l = strlen(c_time_string);
if (l > 0)
c_time_string[l-1] = 0;
DEBUG_LOG("%s: VoodooPS2Daemon 1.7.12 starting...\n", c_time_string);
// first check for trackpad driver
g_ioservice = IOServiceGetMatchingService(0, IOServiceMatching("ApplePS2SynapticsTouchPad"));
if (!g_ioservice)
{
// otherwise, talk to mouse driver
g_ioservice = IOServiceGetMatchingService(0, IOServiceMatching("ApplePS2Mouse"));
if (!g_ioservice)
{
DEBUG_LOG("No ApplePS2SynapticsTouchPad or ApplePS2Mouse found\n");
return -1;
}
}
// Set up a signal handler so we can clean up when we're interrupted from the command line
// or otherwise asked to terminate.
if (SIG_ERR == signal(SIGINT, SignalHandler1))
DEBUG_LOG("Could not establish new SIGINT handler\n");
if (SIG_ERR == signal(SIGTERM, SignalHandler1))
DEBUG_LOG("Could not establish new SIGTERM handler\n");
// First create a master_port for my task
mach_port_t masterPort;
kern_return_t kr = IOMasterPort(MACH_PORT_NULL, &masterPort);
if (kr || !masterPort)
{
DEBUG_LOG("ERR: Couldn't create a master IOKit Port(%08x)\n", kr);
return -1;
}
// Create dictionary to match all USB devices
CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
if (!matchingDict)
{
DEBUG_LOG("Can't create a USB matching dictionary\n");
mach_port_deallocate(mach_task_self(), masterPort);
return -1;
}
// Create a notification port and add its run loop event source to our run loop
// This is how async notifications get set up.
g_NotifyPort = IONotificationPortCreate(masterPort);
CFRunLoopSourceRef runLoopSource = IONotificationPortGetRunLoopSource(g_NotifyPort);
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
CFRunLoopAddSource(runLoop, runLoopSource, kCFRunLoopDefaultMode);
// Now set up a notification to be called when a device is first matched by I/O Kit.
// Note that this will not catch any devices that were already plugged in so we take
// care of those later.
kr = IOServiceAddMatchingNotification(g_NotifyPort, kIOFirstMatchNotification, matchingDict, DeviceAdded, NULL, &g_AddedIter);
// Iterate once to get already-present devices and arm the notification
DeviceAdded(NULL, g_AddedIter);
// Now done with the master_port
mach_port_deallocate(mach_task_self(), masterPort);
masterPort = 0;
// Start the run loop. Now we'll receive notifications.
CFRunLoopRun();
// We should never get here
DEBUG_LOG("Unexpectedly back from CFRunLoopRun()!\n");
return 0;
}
示例11: Tcl_InitNotifier
ClientData
Tcl_InitNotifier(void)
{
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
tsdPtr->eventReady = 0;
#ifdef WEAK_IMPORT_SPINLOCKLOCK
/*
* Initialize support for weakly imported spinlock API.
*/
if (pthread_once(&spinLockLockInitControl, SpinLockLockInit)) {
Tcl_Panic("Tcl_InitNotifier: pthread_once failed");
}
#endif
#ifndef __CONSTANT_CFSTRINGS__
if (!tclEventsOnlyRunLoopMode) {
tclEventsOnlyRunLoopMode = CFSTR(TCL_EVENTS_ONLY_RUN_LOOP_MODE);
}
#endif
/*
* Initialize CFRunLoopSource and add it to CFRunLoop of this thread.
*/
if (!tsdPtr->runLoop) {
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
CFRunLoopSourceRef runLoopSource;
CFRunLoopSourceContext runLoopSourceContext;
bzero(&runLoopSourceContext, sizeof(CFRunLoopSourceContext));
runLoopSourceContext.info = tsdPtr;
runLoopSource = CFRunLoopSourceCreate(NULL, 0, &runLoopSourceContext);
if (!runLoopSource) {
Tcl_Panic("Tcl_InitNotifier: could not create CFRunLoopSource");
}
CFRunLoopAddSource(runLoop, runLoopSource, kCFRunLoopCommonModes);
CFRunLoopAddSource(runLoop, runLoopSource, tclEventsOnlyRunLoopMode);
tsdPtr->runLoopSource = runLoopSource;
tsdPtr->runLoop = runLoop;
}
LOCK_NOTIFIER_INIT;
#ifdef HAVE_PTHREAD_ATFORK
/*
* Install pthread_atfork handlers to reinitialize the notifier in the
* child of a fork.
*/
if (
#ifdef WEAK_IMPORT_PTHREAD_ATFORK
pthread_atfork != NULL &&
#endif
!atForkInit) {
int result = pthread_atfork(AtForkPrepare, AtForkParent, AtForkChild);
if (result) {
Tcl_Panic("Tcl_InitNotifier: pthread_atfork failed");
}
atForkInit = 1;
}
#endif
if (notifierCount == 0) {
int fds[2], status;
/*
* Initialize trigger pipe.
*/
if (pipe(fds) != 0) {
Tcl_Panic("Tcl_InitNotifier: could not create trigger pipe");
}
status = fcntl(fds[0], F_GETFL);
status |= O_NONBLOCK;
if (fcntl(fds[0], F_SETFL, status) < 0) {
Tcl_Panic("Tcl_InitNotifier: could not make receive pipe non blocking");
}
status = fcntl(fds[1], F_GETFL);
status |= O_NONBLOCK;
if (fcntl(fds[1], F_SETFL, status) < 0) {
Tcl_Panic("Tcl_InitNotifier: could not make trigger pipe non blocking");
}
receivePipe = fds[0];
triggerPipe = fds[1];
/*
* Create notifier thread lazily in Tcl_WaitForEvent() to avoid
* interfering with fork() followed immediately by execve()
* (cannot execve() when more than one thread is present).
*/
notifierThread = 0;
}
notifierCount++;
UNLOCK_NOTIFIER_INIT;
return (ClientData) tsdPtr;
}
示例12: rawhid_open
// rawhid_open - open 1 or more devices
//
// Inputs:
// max = maximum number of devices to open
// vid = Vendor ID, or -1 if any
// pid = Product ID, or -1 if any
// usage_page = top level usage page, or -1 if any
// usage = top level usage number, or -1 if any
// Output:
// actual number of devices opened
//
int rawhid_open(int max, int vid, int pid, int usage_page, int usage)
{
//***
kern_return_t result;
mach_port_t masterPort;
CFMutableDictionaryRef matchingDict;
CFRunLoopSourceRef runLoopSource;
//Create a master port for communication with the I/O Kit
result = IOMasterPort(MACH_PORT_NULL, &masterPort);
if (result || !masterPort)
{
return -1;
}
//To set up asynchronous notifications, create a notification port and
//add its run loop event source to the programs run loop
gNotifyPort = IONotificationPortCreate(masterPort);
runLoopSource = IONotificationPortGetRunLoopSource(gNotifyPort);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource,
kCFRunLoopDefaultMode);
// ***
/*
IOServiceAddMatchingNotification(
gNotifyPort,
kIOFirstMatchNotification,
matchingDict,
attach_callback,
NULL,
&gAddedIter);
*/
// ***
static IOHIDManagerRef hid_manager=NULL;
CFMutableDictionaryRef dict;
CFNumberRef num;
IOReturn ret;
hid_t *p;
int count=0;
//fprintf(stderr,"fprintf rawhid_open\n");
if (first_hid) free_all_hid();
//printf("rawhid_open, max=%d\n", max);
//fflush (stdout);
if (max < 1) return 0;
// Start the HID Manager
// http://developer.apple.com/technotes/tn2007/tn2187.html
if (!hid_manager) {
hid_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (hid_manager == NULL || CFGetTypeID(hid_manager) != IOHIDManagerGetTypeID()) {
if (hid_manager) CFRelease(hid_manager);
return 0;
}
}
if (vid > 0 || pid > 0 || usage_page > 0 || usage > 0) {
// Tell the HID Manager what type of devices we want
dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
if (!dict) return 0;
if (vid > 0)
{
num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &vid);
CFDictionarySetValue(dict, CFSTR(kIOHIDVendorIDKey), num);
CFRelease(num);
}
if (pid > 0)
{
num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &pid);
CFDictionarySetValue(dict, CFSTR(kIOHIDProductIDKey), num);
CFRelease(num);
}
if (usage_page > 0)
{
num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage_page);
CFDictionarySetValue(dict, CFSTR(kIOHIDPrimaryUsagePageKey), num);
CFRelease(num);
}
if (usage > 0)
{
num = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage);
CFDictionarySetValue(dict, CFSTR(kIOHIDPrimaryUsageKey), num);
CFRelease(num);
}
IOHIDManagerSetDeviceMatching(hid_manager, dict);
CFRelease(dict);
}
else
{
IOHIDManagerSetDeviceMatching(hid_manager, NULL);
//.........這裏部分代碼省略.........
示例13: main
int main (int argc, const char *argv[])
{
mach_port_t masterPort;
CFMutableDictionaryRef matchingDict;
CFRunLoopSourceRef runLoopSource;
kern_return_t kr;
SInt32 usbVendor = kOurVendorID;
SInt32 usbProduct = kOurProductID;
sig_t oldHandler;
// pick up command line arguments
if (argc > 1)
usbVendor = atoi(argv[1]);
if (argc > 2)
usbProduct = atoi(argv[2]);
// Set up a signal handler so we can clean up when we're interrupted from the command line
// Otherwise we stay in our run loop forever.
oldHandler = signal(SIGINT, SignalHandler);
if (oldHandler == SIG_ERR)
printf("Could not establish new signal handler");
// first create a master_port for my task
kr = IOMasterPort(MACH_PORT_NULL, &masterPort);
if (kr || !masterPort)
{
printf("ERR: Couldn't create a master IOKit Port(%08x)\n", kr);
return -1;
}
printf("Looking for devices matching vendor ID=%ld and product ID=%ld\n", usbVendor, usbProduct);
// Set up the matching criteria for the devices we're interested in
matchingDict = IOServiceMatching(kIOUSBDeviceClassName); // Interested in instances of class IOUSBDevice and its subclasses
if (!matchingDict)
{
printf("Can't create a USB matching dictionary\n");
mach_port_deallocate(mach_task_self(), masterPort);
return -1;
}
// Add our vendor and product IDs to the matching criteria
CFDictionarySetValue(
matchingDict,
CFSTR(kUSBVendorID),
CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usbVendor));
CFDictionarySetValue(
matchingDict,
CFSTR(kUSBProductID),
CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usbProduct));
// Create a notification port and add its run loop event source to our run loop
// This is how async notifications get set up.
gNotifyPort = IONotificationPortCreate(masterPort);
runLoopSource = IONotificationPortGetRunLoopSource(gNotifyPort);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
// Retain additional references because we use this same dictionary with four calls to
// IOServiceAddMatchingNotification, each of which consumes one reference.
matchingDict = (CFMutableDictionaryRef) CFRetain( matchingDict );
matchingDict = (CFMutableDictionaryRef) CFRetain( matchingDict );
matchingDict = (CFMutableDictionaryRef) CFRetain( matchingDict );
// Now set up two notifications, one to be called when a raw device is first matched by I/O Kit, and the other to be
// called when the device is terminated.
kr = IOServiceAddMatchingNotification( gNotifyPort,
kIOFirstMatchNotification,
matchingDict,
RawDeviceAdded,
NULL,
&gRawAddedIter );
RawDeviceAdded(NULL, gRawAddedIter); // Iterate once to get already-present devices and
// arm the notification
kr = IOServiceAddMatchingNotification( gNotifyPort,
kIOTerminatedNotification,
matchingDict,
RawDeviceRemoved,
NULL,
&gRawRemovedIter );
RawDeviceRemoved(NULL, gRawRemovedIter); // Iterate once to arm the notification
// Change the USB product ID in our matching dictionary to the one the device will have once the
// bulktest firmware has been downloaded.
usbProduct = kOurProductIDBulkTest;
CFDictionarySetValue(
matchingDict,
CFSTR(kUSBProductID),
CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usbProduct));
// Now set up two more notifications, one to be called when a bulk test device is first matched by I/O Kit, and the other to be
// called when the device is terminated.
kr = IOServiceAddMatchingNotification( gNotifyPort,
kIOFirstMatchNotification,
matchingDict,
BulkTestDeviceAdded,
//.........這裏部分代碼省略.........
示例14: FindInterfaces
//.........這裏部分代碼省略.........
break;
case kUSBIn:
message = "in";
break;
case kUSBNone:
message = "none";
break;
case kUSBAnyDirn:
message = "any";
break;
default:
message = "???";
}
printf("direction %s, ", message);
switch (transferType) {
case kUSBControl:
message = "control";
break;
case kUSBIsoc:
message = "isoc";
break;
case kUSBBulk:
message = "bulk";
break;
case kUSBInterrupt:
message = "interrupt";
break;
case kUSBAnyType:
message = "any";
break;
default:
message = "???";
}
printf("transfer type %s, maxPacketSize %d\n", message, maxPacketSize);
}
}
// We can now address endpoints 1 through intfNumEndpoints. Or, we can also address endpoint 0,
// the default control endpoint. But it's usually better to use (*usbDevice)->DeviceRequest() instead.
#ifndef USE_ASYNC_IO
kr = (*intf)->WritePipe(intf, 2, kTestMessage, strlen(kTestMessage));
if (kIOReturnSuccess != kr)
{
printf("unable to do bulk write (%08x)\n", kr);
(void) (*intf)->USBInterfaceClose(intf);
(void) (*intf)->Release(intf);
break;
}
printf("Wrote \"%s\" (%ld bytes) to bulk endpoint\n", kTestMessage, (UInt32) strlen(kTestMessage));
numBytesRead = sizeof(gBuffer) - 1; // leave one byte at the end for NUL termination
kr = (*intf)->ReadPipe(intf, 9, gBuffer, &numBytesRead);
if (kIOReturnSuccess != kr)
{
printf("unable to do bulk read (%08x)\n", kr);
(void) (*intf)->USBInterfaceClose(intf);
(void) (*intf)->Release(intf);
break;
}
// The firmware we downloaded echoes the 1's complement of what we wrote, so
// complement the buffer contents to see if we get the original data
for (i = 0; i < numBytesRead; i++)
gBuffer[i] = ~gBuffer[i];
printf("Read \"%s\" (%ld bytes) from bulk endpoint\n", gBuffer, numBytesRead);
#else
// Just like with service matching notifications, we need to create an event source and add it
// to our run loop in order to receive async completion notifications.
kr = (*intf)->CreateInterfaceAsyncEventSource(intf, &runLoopSource);
if (kIOReturnSuccess != kr)
{
printf("unable to create async event source (%08x)\n", kr);
(void) (*intf)->USBInterfaceClose(intf);
(void) (*intf)->Release(intf);
break;
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
printf("Async event source added to run loop.\n");
bzero(gBuffer, sizeof(gBuffer));
strcpy(gBuffer, kTestMessage);
kr = (*intf)->WritePipeAsync(intf, 2, gBuffer, strlen(gBuffer), WriteCompletion, (void *) intf);
if (kIOReturnSuccess != kr)
{
printf("unable to do async bulk write (%08x)\n", kr);
(void) (*intf)->USBInterfaceClose(intf);
(void) (*intf)->Release(intf);
break;
}
#endif
// For this test we just want to use the first interface, so exit the loop.
break;
}
return kr;
}
示例15: main
//================================================================================================
// main
//================================================================================================
int main(int argc, const char *argv[])
{
CFMutableDictionaryRef matchingDict;
CFRunLoopSourceRef runLoopSource;
CFNumberRef numberRef;
kern_return_t kr;
long usbVendor = kMyVendorID;
long usbProduct = kMyProductID;
sig_t oldHandler;
// pick up command line arguments
if (argc > 1) {
usbVendor = atoi(argv[1]);
}
if (argc > 2) {
usbProduct = atoi(argv[2]);
}
// Set up a signal handler so we can clean up when we're interrupted from the command line
// Otherwise we stay in our run loop forever.
oldHandler = signal(SIGINT, SignalHandler);
if (oldHandler == SIG_ERR) {
fprintf(stderr, "Could not establish new signal handler.");
}
fprintf(stderr, "Looking for devices matching vendor ID=%ld and product ID=%ld.\n", usbVendor, usbProduct);
// Set up the matching criteria for the devices we're interested in. The matching criteria needs to follow
// the same rules as kernel drivers: mainly it needs to follow the USB Common Class Specification, pp. 6-7.
// See also Technical Q&A QA1076 "Tips on USB driver matching on Mac OS X"
// <http://developer.apple.com/qa/qa2001/qa1076.html>.
// One exception is that you can use the matching dictionary "as is", i.e. without adding any matching
// criteria to it and it will match every IOUSBDevice in the system. IOServiceAddMatchingNotification will
// consume this dictionary reference, so there is no need to release it later on.
matchingDict = IOServiceMatching(kIOUSBDeviceClassName); // Interested in instances of class
// IOUSBDevice and its subclasses
if (matchingDict == NULL) {
fprintf(stderr, "IOServiceMatching returned NULL.\n");
return -1;
}
// We are interested in all USB devices (as opposed to USB interfaces). The Common Class Specification
// tells us that we need to specify the idVendor, idProduct, and bcdDevice fields, or, if we're not interested
// in particular bcdDevices, just the idVendor and idProduct. Note that if we were trying to match an
// IOUSBInterface, we would need to set more values in the matching dictionary (e.g. idVendor, idProduct,
// bInterfaceNumber and bConfigurationValue.
// Create a CFNumber for the idVendor and set the value in the dictionary
numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usbVendor);
CFDictionarySetValue(matchingDict,
CFSTR(kUSBVendorID),
numberRef);
CFRelease(numberRef);
// Create a CFNumber for the idProduct and set the value in the dictionary
numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &usbProduct);
CFDictionarySetValue(matchingDict,
CFSTR(kUSBProductID),
numberRef);
CFRelease(numberRef);
numberRef = NULL;
// Create a notification port and add its run loop event source to our run loop
// This is how async notifications get set up.
gNotifyPort = IONotificationPortCreate(kIOMasterPortDefault);
runLoopSource = IONotificationPortGetRunLoopSource(gNotifyPort);
gRunLoop = CFRunLoopGetCurrent();
CFRunLoopAddSource(gRunLoop, runLoopSource, kCFRunLoopDefaultMode);
// Now set up a notification to be called when a device is first matched by I/O Kit.
kr = IOServiceAddMatchingNotification(gNotifyPort, // notifyPort
kIOFirstMatchNotification, // notificationType
matchingDict, // matching
DeviceAdded, // callback
NULL, // refCon
&gAddedIter // notification
);
// Iterate once to get already-present devices and arm the notification
DeviceAdded(NULL, gAddedIter);
// Start the run loop. Now we'll receive notifications.
fprintf(stderr, "Starting run loop.\n\n");
CFRunLoopRun();
// We should never get here
fprintf(stderr, "Unexpectedly back from CFRunLoopRun()!\n");
return 0;
}