int main(void) { dispatch_queue_t q = dispatch_get_main_queue(); test_start("Dispatch (Public) API"); test_ptr_notnull("dispatch_get_main_queue", q); dispatch_async_f(dispatch_get_main_queue(), NULL, work); dispatch_main(); }
extern "C" void Qt_dispatch_source_signal_lambda(){ char argv[] = "test"; int argc = 1; QDispatchApplication app(argc, (char**)&argv); MU_BEGIN_TEST(Qt_dispatch_source_signal_lambda); EmitterLambda object; // configure the source QDispatchSource src(new QDispatchSourceTypeSignal(&object, SIGNAL(ready()))); src.setTargetQueue(QDispatch::globalQueue(QDispatch::LOW)); src.setHandler([=]{ MU_MESSAGE("Signal was emitted"); if(QDispatch::currentQueue().native() == dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) MU_MESSAGE("Executed on low global queue"); else if(QDispatch::currentQueue().native() == dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) MU_MESSAGE("Executed on default global queue"); else if(QDispatch::currentQueue().native() == dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) MU_MESSAGE("Executed on high global queue"); else if(QDispatch::currentQueue().native() == dispatch_get_main_queue()) MU_MESSAGE("Executed on main queue"); MU_ASSERT_EQUAL_HEX(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), QDispatch::currentQueue().native()); MU_PASS(""); }); // trigger the signal object.notify(); app.exec(); MU_END_TEST; }
void test_timer(void) { dispatch_test_start("Dispatch Update Timer"); dispatch_queue_t main_q = dispatch_get_main_queue(); //test_ptr("dispatch_get_main_queue", main_q, dispatch_get_current_queue()); __block int i = 0; struct timeval start_time; gettimeofday(&start_time, NULL); dispatch_source_t s = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, main_q); test_ptr_notnull("dispatch_source_create", s); dispatch_source_set_timer(s, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), NSEC_PER_SEC, 0); dispatch_source_set_cancel_handler(s, ^{ struct timeval end_time; gettimeofday(&end_time, NULL); // Make sure we actually managed to adjust the interval // duration. Seven one second ticks would blow past // this. test_long_less_than("total duration", end_time.tv_sec - start_time.tv_sec, 3); test_stop(); dispatch_release(s); });
int main(int argc, char* argv[]) { // interval is 1/10th of a second uint64_t interval = NSEC_PER_SEC / 10; // for 25 seconds struct timeval now_tv; struct timespec now_ts; interval_d = (double)interval / (double)NSEC_PER_SEC; target = (unsigned int)(25 / interval_d); test_start("Timer drift test"); timeBeginPeriod(1); timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); test_ptr_notnull("DISPATCH_SOURCE_TYPE_TIMER", timer); dispatch_source_set_event_handler_f(timer, timer_handler); gettimeofday(&now_tv, NULL); now_ts.tv_sec = now_tv.tv_sec; now_ts.tv_nsec = now_tv.tv_usec * NSEC_PER_USEC; dispatch_source_set_timer(timer, dispatch_walltime(&now_ts, interval), interval, 0); dispatch_resume(as_do(timer)); dispatch_main(); return 0; }
bool AXLibInitializeApplication(pid_t PID) { ax_application *Application = AXLibGetApplicationByPID(PID); if(Application) { bool Result = AXLibAddApplicationObserver(Application); if(Result) { AXLibAddApplicationWindows(Application); Application->Focus = AXLibGetFocusedWindow(Application); } else { AXLibRemoveApplicationObserver(Application); if(++Application->Retries < AX_APPLICATION_RETRIES) { #ifdef DEBUG_BUILD printf("AX: %s - Not responding, retry %d\n", Application->Name.c_str(), Application->Retries); #endif dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ if(AXLibInitializeApplication(PID)) { AXLibInitializedApplication(Application); } }); } else {
static void do_test(void) { size_t i; char buf[1000]; dispatch_group_t g = dispatch_group_create(); for (i = 0; i < QUEUES; i++) { #ifdef WIN32 _snprintf(buf, sizeof(buf), "com.example.memoryload-node#%ld", i); #else snprintf(buf, sizeof(buf), "com.example.memoryload-node#%ld", (long int)i); #endif queues[i] = dispatch_queue_create(buf, NULL); dispatch_suspend(queues[i]); } for (i = 0; i < QUEUES; i++) { dispatch_group_async_f(g, queues[i], g, start_node); } dispatch_group_notify_f(g, dispatch_get_main_queue(), NULL, collect); for (i = 0; i < QUEUES; i++) { dispatch_resume(queues[i]); dispatch_release(queues[i]); } }
void run(){ // we should be executed on the main queue MU_ASSERT_EQUAL_HEX(QDispatch::currentQueue().native(), dispatch_get_main_queue()); // assert that we can really get the timer MU_ASSERT_EQUAL_HEX(QDispatchTimer::current(), tested_timer); // test the timer interval (but only after the second run // as the first one will be started immediately if(counter > 0) { long diff = checked_time.elapsed(); MU_DESC_ASSERT_LESS_THAN_EQUAL("timer not too late", diff, 3*1000); MU_DESC_ASSERT_LESS_THAN_EQUAL("timer not too early", 1*1000, diff); } checked_time.restart(); // only pass when the timer fired at least 5 times MU_MESSAGE("\t%i", counter); if(counter < 5) counter++; else { MU_PASS(""); } }
int main(void) { test_start("Dispatch After"); dispatch_async_f(dispatch_get_main_queue(), NULL, func_outer); dispatch_main(); }
/***************************************************************************** * NetBrowserInfoCreate * - * The method creates a NetBrowserInfo Object and initalizes it. *****************************************************************************/ NetBrowserInfo* NetBrowserInfoCreate(CFStringRef serviceType, CFStringRef domain, void* context) { NetBrowserInfo* outObj = NULL; DNSServiceRef browserRef = NULL; char* cServiceType = NULL; char* cDomain = NULL; Boolean success = true; CFIndex serviceSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(serviceType), kCFStringEncodingUTF8); cServiceType = calloc(serviceSize, 1); success = CFStringGetCString(serviceType, cServiceType, serviceSize, kCFStringEncodingUTF8); if (domain) { CFIndex domainSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(domain), kCFStringEncodingUTF8); cDomain = calloc(serviceSize, 1); success = success && CFStringGetCString(domain, cDomain, domainSize, kCFStringEncodingUTF8); } if (!success) { fprintf(stderr, "LaunchEvent has badly encoded service type or domain.\n"); free(cServiceType); if (cDomain) free(cDomain); return NULL; } DNSServiceErrorType err = DNSServiceBrowse(&browserRef, 0, 0, cServiceType, cDomain, ServiceBrowserCallback, context); if (err != kDNSServiceErr_NoError) { fprintf(stderr, "Failed to create browser for %s, %s\n", cServiceType, cDomain); free(cServiceType); if (cDomain) free(cDomain); return NULL; } DNSServiceSetDispatchQueue(browserRef, dispatch_get_main_queue()); outObj = malloc(sizeof(NetBrowserInfo)); outObj->refCount = 1; outObj->browserRef = browserRef; free(cServiceType); if (cDomain) free(cDomain); return outObj; }
static void dump_watch_run() { if (!last_finished_dump) return; if (dump_in_progress || (time(NULL) - last_finished_dump < 0.5)) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^ { dump_watch_run(); });
void dispatch_after_function() { MU_BEGIN_TEST(dispatch_after); dispatch_async_f(dispatch_get_main_queue(),NULL,dispatch_start); dispatch_main(); MU_FAIL("Should never reach this"); MU_END_TEST; }
internal void CarbonApplicationLaunched(ProcessSerialNumber PSN) { Str255 ProcessName = {}; ProcessInfoRec ProcessInfo = {}; ProcessInfo.processInfoLength = sizeof(ProcessInfoRec); ProcessInfo.processName = ProcessName; /* NOTE(koekeishiya): Deprecated, consider switching to * CFDictionaryRef ProcessInformationCopyDictionary(const ProcessSerialNumber *PSN, UInt32 infoToReturn) */ GetProcessInformation(&PSN, &ProcessInfo); char ProcessNameCString[256] = {0}; if(ProcessInfo.processName) CopyPascalStringToC(ProcessInfo.processName, ProcessNameCString); std::string Name = ProcessNameCString; /* NOTE(koekeishiya): Check if we should care about this process. */ if((!IsProcessWhitelisted(Name)) && ((ProcessInfo.processMode & modeOnlyBackground) != 0)) return; pid_t PID = 0; GetProcessPID(&PSN, &PID); /* printf("Carbon: Application launched %s\n", Name.c_str()); printf("%d: modeReserved\n", ProcessInfo.processMode & modeReserved); printf("%d: modeControlPanel\n", ProcessInfo.processMode & modeControlPanel); printf("%d: modeLaunchDontSwitch\n", ProcessInfo.processMode & modeLaunchDontSwitch); printf("%d: modeDeskAccessory\n", ProcessInfo.processMode & modeDeskAccessory); printf("%d: modeMultiLaunch\n", ProcessInfo.processMode & modeMultiLaunch); printf("%d: modeNeedSuspendResume\n", ProcessInfo.processMode & modeNeedSuspendResume); printf("%d: modeCanBackground\n", ProcessInfo.processMode & modeCanBackground); printf("%d: modeDoesActivateOnFGSwitch\n", ProcessInfo.processMode & modeDoesActivateOnFGSwitch); printf("%d: modeOnlyBackground\n", ProcessInfo.processMode & modeOnlyBackground); printf("%d: modeGetFrontClicks\n", ProcessInfo.processMode & modeGetFrontClicks); printf("%d: modeGetAppDiedMsg\n", ProcessInfo.processMode & modeGetAppDiedMsg); printf("%d: mode32BitCompatible\n", ProcessInfo.processMode & mode32BitCompatible); printf("%d: modeHighLevelEventAware\n", ProcessInfo.processMode & modeHighLevelEventAware); printf("%d: modeLocalAndRemoteHLEvents\n", ProcessInfo.processMode & modeLocalAndRemoteHLEvents); printf("%d: modeStationeryAware\n", ProcessInfo.processMode & modeStationeryAware); printf("%d: modeUseTextEditServices\n", ProcessInfo.processMode & modeUseTextEditServices); printf("%d: modeDisplayManagerAware\n", ProcessInfo.processMode & modeDisplayManagerAware); */ (*Applications)[PID] = AXLibConstructApplication(PID, Name); ax_application *Application = &(*Applications)[PID]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ if(AXLibInitializeApplication(Application->PID)) AXLibInitializedApplication(Application); });
static mrb_value mrb_queue_main(mrb_state *mrb, mrb_value self) { mrb_value instance; dispatch_queue_t q; instance = mrb_queue_create_instance(mrb); q = dispatch_get_main_queue(); return mrb_queue_set_queue(instance, q); }
static void pong(void *context) { dispatch_queue_t this_q = (dispatch_queue_t)context; size_t replies = (size_t)dispatch_get_context(this_q); dispatch_set_context(this_q, (void *)--replies); if (!replies) { //MU_MESSAGE("collect from: %s\n", dispatch_queue_get_label(dispatch_get_current_queue())); dispatch_async_f(dispatch_get_main_queue(), NULL, collect); } }
int main(void) { const char *path = "/usr/share/dict/words"; struct stat sb; dispatch_test_start("Dispatch Source Read"); int infd = open(path, O_RDONLY); if (infd == -1) { perror(path); exit(EXIT_FAILURE); } if (fstat(infd, &sb) == -1) { perror(path); exit(EXIT_FAILURE); } bytes_total = sb.st_size; if (fcntl(infd, F_SETFL, O_NONBLOCK) != 0) { perror(path); exit(EXIT_FAILURE); } if (!dispatch_test_check_evfilt_read_for_fd(infd)) { test_skip("EVFILT_READ kevent not firing for test file"); test_fin(NULL); } dispatch_queue_t main_q = dispatch_get_main_queue(); test_ptr_notnull("dispatch_get_main_queue", main_q); dispatch_source_t reader = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, infd, 0, main_q); test_ptr_notnull("dispatch_source_create", reader); assert(reader); dispatch_source_set_event_handler(reader, ^{ size_t estimated = dispatch_source_get_data(reader); fprintf(stderr, "bytes available: %zu\n", estimated); test_double_less_than_or_equal("estimated", estimated, bytes_total - bytes_read); const ssize_t bufsiz = 1024*500; // 500 KB buffer static char buffer[1024*500]; // 500 KB buffer ssize_t actual = read(infd, buffer, sizeof(buffer)); bytes_read += actual; printf("bytes read: %zd\n", actual); if (actual < bufsiz) { actual = read(infd, buffer, sizeof(buffer)); bytes_read += actual; // confirm EOF condition test_long("EOF", actual, 0); dispatch_source_cancel(reader); } });
void save_image(ConvertContext *context) { int result = RESULT_OK; char *error_desc; ExceptionType error_type; // get pixel data if (context->hasAlphaChannel == MagickTrue) { if (MagickImportImagePixels(context->mw, 0, 0, context->imageWidth, context->imageHeight, "ARGB", CharPixel, context->pixels) == MagickFalse) { error_desc = MagickGetException(context->mw, &error_type); asprintf(&context->results.message, "Error exporting pixel data (%s): %s\n",error_desc,context->src_path); error_desc = (char *)MagickRelinquishMemory(error_desc); result += RESULT_ERROR; } } // convert image to PNG if (result == RESULT_OK) { if (MagickSetImageFormat(context->mw,"PNG") == MagickFalse) { error_desc = MagickGetException(context->mw, &error_type); asprintf(&context->results.message,"Error converting image (%s): %s\n",error_desc,context->src_path); error_desc = (char *)MagickRelinquishMemory(error_desc); result += RESULT_ERROR; } } // activate/deactivate alpha channel MagickSetImageAlphaChannel(context->mw, (context->results.alpha_type == ALPHA_TYPE_NONE ? DeactivateAlphaChannel : ActivateAlphaChannel)); // make sure image is saved as RGB and not crunched down to grayscale MagickSetType(context->mw, (context->results.alpha_type == ALPHA_TYPE_NONE ? TrueColorType : TrueColorMatteType)); // save image to disk if (result == RESULT_OK) { if (MagickWriteImage(context->mw, context->dst_path) == MagickFalse) { error_desc = MagickGetException(context->mw, &error_type); asprintf(&context->results.message, "Error saving image (%s): %s\n",error_desc,context->dst_path); error_desc = (char *)MagickRelinquishMemory(error_desc); result += RESULT_ERROR; } } if (result == RESULT_OK && context->options.delete_original != 0) { if (unlink(context->src_path) == -1) { asprintf(&context->results.message, "Unable to delete original image (%s): %s\n", strerror(errno), context->src_path); result += RESULT_ERROR; } } // cleanup and report results context->results.result = result; dispatch_group_async_f(context->conv_group, dispatch_get_main_queue(), context, (void (*)(void *))finish_image); }
// TODO: come up with calling scheme, friending doesn't seem to be possible :( void ofxGenericApp::finishedLaunching() { if ( getWindow() ) { _windowSize = getWindow()->getFrame(); } handleFinishedLaunchingPresetup(); // wait a cycle so iOS has time to get initialized dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ setup(); });
static void collect(void *context) { MU_MESSAGE("All workers done."); // give the threads some time to settle before test_stop() runs "leaks" // ...also note, this is a total cheat. dispatch_after lets this // thread go idle, so dispatch cleans up the continuations cache. // Doign the "old style" sleep left that stuff around and leaks // took a LONG TIME to complete. Long enough that the test harness // decided to kill us. dispatch_after_f(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), NULL, MU_PASS_AFTER_DELAY); }
/****************************************************************************** * _kextmanager_lock_volume tries to lock volumes for clients (kextutil) *****************************************************************************/ kern_return_t _kextmanager_lock_kextload( mach_port_t server, mach_port_t client, int * lockstatus) { kern_return_t mig_result = KERN_FAILURE; int result; if (!lockstatus) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogIPCFlag, "kextmanager_lock_kextload requires non-NULL lockstatus."); mig_result = KERN_SUCCESS; result = EINVAL; goto finish; } if (gClientUID != 0) { OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel, "Non-root process doesn't need to lock as it will fail to load."); mig_result = KERN_SUCCESS; result = EPERM; goto finish; } if (_gKextutilLock) { mig_result = KERN_SUCCESS; result = EBUSY; goto finish; } result = ENOMEM; _gKextutilLock = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_SEND, client, DISPATCH_MACH_SEND_DEAD, dispatch_get_main_queue()); if (_gKextutilLock) { dispatch_source_set_event_handler(_gKextutilLock, ^{ OSKextLog(/* kext */ NULL, kOSKextLogErrorLevel | kOSKextLogIPCFlag, "Client exited without releasing kextutil lock."); removeKextutilLock(); }); dispatch_source_set_cancel_handler(_gKextutilLock, ^{ dispatch_release(_gKextutilLock); mach_port_deallocate(mach_task_self(), client); _gKextutilLock = NULL; });
extern "C" void dispatch_plusplus_blocks(void) { MU_BEGIN_TEST(dispatch_plusplus_blocks); dispatch_queue_t q = dispatch_get_main_queue(); MU_ASSERT_NOT_NULL(q); dispatch_async(dispatch_get_main_queue(), ^{ int i = 0; i++; MU_ASSERT_EQUAL(i, 1); const char* pass = "******"; MU_PASS(pass); });
extern "C" void dispatch_after_lambda(void) { MU_BEGIN_TEST(dispatch_after_lambda); dispatch_async(dispatch_get_main_queue(), [=]{ dispatch_time_t time_a_min = dispatch_time(0, 5.5*NSEC_PER_SEC); dispatch_time_t time_a = dispatch_time(0, 6.0*NSEC_PER_SEC); dispatch_time_t time_a_max = dispatch_time(0, 6.5*NSEC_PER_SEC); dispatch_time_t time_a_start = dispatch_time(0,0); dispatch_after(time_a, dispatch_get_current_queue(), [=]{ dispatch_time_t now_a = dispatch_time(0, 0); MU_MESSAGE("must finish between 5.5s and 6.5s: %f",(now_a-time_a_start)/(float)NSEC_PER_SEC); MU_ASSERT_TRUE(0<=(now_a - time_a_min)); MU_ASSERT_TRUE(0<=(time_a_max - now_a)); dispatch_time_t time_b_min = dispatch_time(0, 1.5*NSEC_PER_SEC); dispatch_time_t time_b = dispatch_time(0, 2*NSEC_PER_SEC); dispatch_time_t time_b_max = dispatch_time(0, 2.5*NSEC_PER_SEC); dispatch_time_t time_b_start = dispatch_time(0,0); dispatch_after(time_b, dispatch_get_current_queue(), [=]{ dispatch_time_t now_b = dispatch_time(0, 0); MU_MESSAGE("must finish between 1.5s and 2.5s: %f",(now_b-time_b_start)/(float)NSEC_PER_SEC); MU_ASSERT_TRUE(0<=(now_b - time_b_min)); MU_ASSERT_TRUE(0<=(time_b_max - now_b)); #if 1 // FIXME: Nesting three lambdas seems to be broken... dispatch_time_t time_c_min = dispatch_time(0, 0*NSEC_PER_SEC); dispatch_time_t time_c = dispatch_time(0, 0*NSEC_PER_SEC); dispatch_time_t time_c_max = dispatch_time(0, .5*NSEC_PER_SEC); dispatch_time_t time_c_start = dispatch_time(0, 0); dispatch_after(time_c, dispatch_get_current_queue(), [=]{ dispatch_time_t now_c = dispatch_time(0, 0); MU_MESSAGE("must finish between 0s and .5s: %f",(now_c-time_c_start)/(float)NSEC_PER_SEC); MU_ASSERT_TRUE(0<=(now_c - time_c_min)); MU_ASSERT_TRUE(0<=(time_c_max - now_c)); dispatch_async_f(dispatch_get_current_queue(), NULL, done); }); #else dispatch_async_f(dispatch_get_current_queue(), NULL, done); #endif }); }); }); dispatch_main(); MU_FAIL("Should never reach this"); MU_END_TEST; }
void load_image(ConvertContext *context) { int result = RESULT_OK; char *error_desc; ExceptionType error_type; // wait for resources to be available dispatch_semaphore_wait(context->conv_semaphore, DISPATCH_TIME_FOREVER); // load image if (MagickReadImage(context->mw, context->src_path) == MagickFalse) { // deal with error error_desc = MagickGetException(context->mw, &error_type); asprintf(&context->results.message,"Error loading image (%s): %s\n",error_desc,context->src_path); error_desc = (char *)MagickRelinquishMemory(error_desc); result += RESULT_ERROR; } if (result == RESULT_OK) { // get image info context->hasAlphaChannel = MagickGetImageAlphaChannel(context->mw); if (context->hasAlphaChannel == MagickTrue) { context->imageWidth = MagickGetImageWidth(context->mw); context->imageHeight = MagickGetImageHeight(context->mw); // get pixel data context->pixel_count = context->imageWidth * context->imageHeight; context->pixels = malloc(context->pixel_count * sizeof(PixelData)); if (context->pixels == NULL) { asprintf(&context->results.message, "Error allocating memory for pixel data: %s\n",context->src_path); result += RESULT_ERROR; } else { if (MagickExportImagePixels(context->mw, 0, 0, context->imageWidth, context->imageHeight, "ARGB", CharPixel, context->pixels) == MagickFalse) { error_desc = MagickGetException(context->mw, &error_type); asprintf(&context->results.message, "Error exporting pixel data (%s): %s\n",error_desc,context->src_path); error_desc = (char *)MagickRelinquishMemory(error_desc); result += RESULT_ERROR; } } } } if (result != RESULT_OK) { // clean up mess context->results.result = result; dispatch_group_async_f(context->conv_group, dispatch_get_main_queue(), context, (void (*)(void *))finish_image); } else { // move to next step dispatch_group_async_f(context->conv_group, context->conv_queue, context, (void (*)(void *))conv_image); } }
BumpArena::BumpArena() { #if DEBUG_BUMPARENA arenas().add(this); static std::once_flag once; std::call_once(once, [] { int d; notify_register_dispatch("com.apple.WebKit.BumpArena.Dump", &d, dispatch_get_main_queue(), ^(int) { for (BumpArena* arena : arenas()) { if (&globalArena() == arena) continue; arena->dump(); } globalArena().dump(); }); });
int main(void) { test_start("Dispatch Suspend Timer"); dispatch_queue_t main_q = dispatch_get_main_queue(); test_ptr("dispatch_get_main_queue", main_q, dispatch_get_current_queue()); __block int i = 0; __block int j = 0; dispatch_source_attr_t attr = dispatch_source_attr_create(); test_ptr_notnull("dispatch_source_attr_create", attr); dispatch_source_attr_set_finalizer(attr, ^(dispatch_source_t ds) { test_ptr_notnull("finalizer ran", ds); if (ds == tweedledum) test_stop(); });
int main(int argc, char *argv[]) { dispatch_source_t tmp_ds; int res; pid_t pid; if (argc < 2) { fprintf(stderr, "usage: harness [...]\n"); exit(1); } posix_spawnattr_t attr; res = posix_spawnattr_init(&attr); assert(res == 0); res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_START_SUSPENDED); assert(res == 0); int i; char** newargv = calloc(argc, sizeof(void*)); for (i = 1; i < argc; ++i) { newargv[i-1] = argv[i]; } newargv[i-1] = NULL; res = posix_spawnp(&pid, newargv[0], NULL, &attr, newargv, environ); if (res) { errno = res; perror(newargv[0]); exit(EXIT_FAILURE); } //fprintf(stderr, "pid = %d\n", pid); assert(pid > 0); dispatch_queue_t main_q = dispatch_get_main_queue(); tmp_ds = dispatch_source_proc_create(pid, DISPATCH_PROC_EXIT, NULL, main_q, ^(dispatch_event_t ev __attribute__((unused))) { int status; int res2 = waitpid(pid, &status, 0); assert(res2 != -1); //int passed = (WIFEXITED(status) && WEXITSTATUS(status) == 0); test_long("Process exited", WEXITSTATUS(status) | WTERMSIG(status), 0); exit(0); });
void dispatch_group_function() { long res; dispatch_group_t group; MU_BEGIN_TEST(dispatch_group_function); group = create_group(100, 0); MU_ASSERT_NOT_NULL(group); dispatch_group_wait(group, DISPATCH_TIME_FOREVER); // should be OK to re-use a group dispatch_group_async_f(group, dispatch_get_global_queue(0, 0), 0, foo); dispatch_group_wait(group, DISPATCH_TIME_FOREVER); dispatch_release(group); group = NULL; group = create_group(3, 7); MU_ASSERT_NOT_NULL(group); res = dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, 5ull * NSEC_PER_SEC)); MU_ASSERT_EQUAL(!res, 0); // retry after timeout (this time succeed) res = dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, 5ull * NSEC_PER_SEC)); MU_ASSERT_EQUAL(res, 0); dispatch_release(group); group = NULL; group = create_group(100, 0); MU_ASSERT_NOT_NULL(group); dispatch_group_notify_f(group, dispatch_get_main_queue(), 0, group_notify); dispatch_release(group); group = NULL; dispatch_main(); MU_FAIL("Should never reach this"); MU_END_TEST }
void test_timer(void) { dispatch_test_start("Dispatch Source Timer, bit 31"); dispatch_queue_t main_q = dispatch_get_main_queue(); //test_ptr("dispatch_get_main_queue", main_q, dispatch_get_current_queue()); struct timeval start_time; static dispatch_source_t s; s = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, main_q); test_ptr_notnull("dispatch_source_create", s); dispatch_source_set_timer(s, dispatch_time(DISPATCH_TIME_NOW, 0x80000000ull), 0x80000000ull, 0); gettimeofday(&start_time, NULL); dispatch_source_set_event_handler(s, ^{ dispatch_source_cancel(s); });
void test_timer(void) { dispatch_test_start("Dispatch Suspend Timer"); dispatch_queue_t main_q = dispatch_get_main_queue(); //test_ptr("dispatch_get_main_queue", main_q, dispatch_get_current_queue()); __block int i = 0, i_prime = 0; __block int j = 0; tweedledee = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, main_q); test_ptr_notnull("dispatch_source_timer_create", tweedledee); dispatch_source_set_timer(tweedledee, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), NSEC_PER_SEC, 0); dispatch_source_set_cancel_handler(tweedledee, ^ { dispatch_release(tweedledee); });
void dispatch_api() { dispatch_queue_t q = NULL; MU_BEGIN_TEST(dispatch_api); q = dispatch_get_main_queue(); MU_DESC_ASSERT_NOT_NULL_HEX("dispatch_get_main_queue",q); dispatch_async_f(q, NULL, pass); q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0); MU_DESC_ASSERT_NOT_NULL_HEX("dispatch_get_global_queue", q); q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW,0); MU_DESC_ASSERT_NOT_NULL_HEX("dispatch_get_global_queue", q); q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0); MU_DESC_ASSERT_NOT_NULL_HEX("dispatch_get_global_queue", q); dispatch_main(); MU_END_TEST; }
static void nc_watch(int argc, char **argv) { SCNetworkConnectionStatus status; nc_create_connection(argc, argv, TRUE); status = SCNetworkConnectionGetStatus(connection); // report initial status n_callback = 0; nc_callback(connection, status, &n_callback); // setup watcher if (doDispatch) { if (!SCNetworkConnectionSetDispatchQueue(connection, dispatch_get_main_queue())) { SCPrint(TRUE, stderr, CFSTR("Unable to schedule watch process: %s\n"), SCErrorString(SCError())); exit(1); } } else { if (!SCNetworkConnectionScheduleWithRunLoop(connection, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) { SCPrint(TRUE, stderr, CFSTR("Unable to schedule watch process: %s\n"), SCErrorString(SCError())); exit(1); } } // wait for changes CFRunLoopRun(); nc_release_connection(); exit(0); }