]> git.saurik.com Git - apple/libdispatch.git/blob - testing/harness.c
libdispatch-84.5.3.tar.gz
[apple/libdispatch.git] / testing / harness.c
1 #include <dispatch/dispatch.h>
2 #include <assert.h>
3 #include <spawn.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7 #include <signal.h>
8 #include <mach/clock_types.h>
9
10 #include "dispatch_test.h"
11
12 extern char **environ;
13
14 int
15 main(int argc, char *argv[])
16 {
17 dispatch_source_t tmp_ds;
18 int res;
19 pid_t pid;
20
21 if (argc < 2) {
22 fprintf(stderr, "usage: harness [...]\n");
23 exit(1);
24 }
25
26 posix_spawnattr_t attr;
27 res = posix_spawnattr_init(&attr);
28 assert(res == 0);
29 res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_START_SUSPENDED);
30 assert(res == 0);
31
32 int i;
33 char** newargv = calloc(argc, sizeof(void*));
34 for (i = 1; i < argc; ++i) {
35 newargv[i-1] = argv[i];
36 }
37 newargv[i-1] = NULL;
38
39 res = posix_spawnp(&pid, newargv[0], NULL, &attr, newargv, environ);
40 if (res) {
41 errno = res;
42 perror(newargv[0]);
43 exit(EXIT_FAILURE);
44 }
45 //fprintf(stderr, "pid = %d\n", pid);
46 assert(pid > 0);
47
48 dispatch_queue_t main_q = dispatch_get_main_queue();
49
50 tmp_ds = dispatch_source_proc_create(pid, DISPATCH_PROC_EXIT, NULL, main_q,
51 ^(dispatch_event_t ev __attribute__((unused))) {
52 int status;
53 int res2 = waitpid(pid, &status, 0);
54 assert(res2 != -1);
55 //int passed = (WIFEXITED(status) && WEXITSTATUS(status) == 0);
56 test_long("Process exited", WEXITSTATUS(status) | WTERMSIG(status), 0);
57 exit(0);
58 });
59 assert(tmp_ds);
60
61 uint64_t timeout = 30LL * NSEC_PER_SEC;
62
63 tmp_ds = dispatch_source_timer_create(DISPATCH_TIMER_ONESHOT, timeout, 0, NULL, main_q,
64 ^(dispatch_event_t ev __attribute__((unused))) {
65 kill(pid, SIGKILL);
66 fprintf(stderr, "Terminating unresponsive process (%0.1lfs)\n", (double)timeout/NSEC_PER_SEC);
67 });
68 assert(tmp_ds);
69
70 signal(SIGINT, SIG_IGN);
71 tmp_ds = dispatch_source_signal_create(SIGINT, NULL, main_q,
72 ^(dispatch_event_t ev __attribute__((unused))) {
73 fprintf(stderr, "Terminating process due to signal\n");
74 kill(pid, SIGKILL);
75 });
76 assert(tmp_ds);
77
78 kill(pid, SIGCONT);
79
80 dispatch_main();
81
82 return 0;
83 }