-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGCDTask.m
200 lines (161 loc) · 5.94 KB
/
GCDTask.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
//
// GCDTask.m
//
// Author: Darvell Long
// Copyright (c) 2014 Reliablehosting.com. All rights reserved.
//
#import "GCDTask.h"
#define GCDTASK_BUFFER_MAX 4096
@implementation GCDTask
- (id) init
{
return [super init];
}
- (void) launchWithOutputBlock: (void (^)(NSData* stdOutData)) stdOut
andErrorBlock: (void (^)(NSData* stdErrData)) stdErr
onLaunch: (void (^)()) launched
onExit: (void (^)()) exit
{
executingTask = [[NSTask alloc] init];
/* Set launch path. */
[executingTask setLaunchPath:[_launchPath stringByStandardizingPath]];
if (![[NSFileManager defaultManager] isExecutableFileAtPath:[executingTask launchPath]])
{
@throw [NSException exceptionWithName:@"GCDTASK_INVALID_EXECUTABLE" reason:@"There is no executable at the path set." userInfo:nil];
}
/* Clean then set arguments. */
for (id arg in _arguments)
{
if([arg class] != [NSString class])
{
NSMutableArray* cleanedArray = [[NSMutableArray alloc] init];
/* Clean up required! */
for (id arg in _arguments)
{
[cleanedArray addObject:[NSString stringWithFormat:@"%@",arg]];
}
[self setArguments:cleanedArray];
break;
}
}
[executingTask setArguments:_arguments];
/* Setup pipes */
stdinPipe = [NSPipe pipe];
stdoutPipe = [NSPipe pipe];
stderrPipe = [NSPipe pipe];
[executingTask setStandardInput:stdinPipe];
[executingTask setStandardOutput:stdoutPipe];
[executingTask setStandardError:stderrPipe];
/* Set current directory, just pass on our actual CWD. */
/* TODO: Potentially make this changeable? Surely there's probably a nicer way to get the CWD too. */
[executingTask setCurrentDirectoryPath:[[[NSFileManager alloc] init] currentDirectoryPath]];
/* Ensure the pipes are non-blocking so GCD can read them correctly. */
fcntl([stdoutPipe fileHandleForReading].fileDescriptor, F_SETFL, O_NONBLOCK);
fcntl([stderrPipe fileHandleForReading].fileDescriptor, F_SETFL, O_NONBLOCK);
/* Setup a dispatch source for both descriptors. */
_stdoutSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ,[stdoutPipe fileHandleForReading].fileDescriptor, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
_stderrSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ,[stderrPipe fileHandleForReading].fileDescriptor, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
/* Set stdout source event handler to read data and send it out. */
dispatch_source_set_event_handler(_stdoutSource, ^ {
void* buffer = malloc(GCDTASK_BUFFER_MAX);
ssize_t bytesRead;
do
{
errno = 0;
bytesRead = read([stdoutPipe fileHandleForReading].fileDescriptor, buffer, GCDTASK_BUFFER_MAX);
} while(bytesRead == -1 && errno == EINTR);
if(bytesRead > 0)
{
// Create before dispatch to prevent a race condition.
NSData* dataToPass = [NSData dataWithBytes:buffer length:bytesRead];
dispatch_async(dispatch_get_main_queue(), ^{
if(!_hasExecuted)
{
if(launched)
launched();
_hasExecuted = TRUE;
}
if(stdOut)
{
stdOut(dataToPass);
}
});
}
if(errno != 0 && bytesRead <= 0)
{
dispatch_source_cancel(_stdoutSource);
dispatch_async(dispatch_get_main_queue(), ^{
if(exit)
exit();
});
}
free(buffer);
});
/* Same thing for stderr. */
dispatch_source_set_event_handler(_stderrSource, ^ {
void* buffer = malloc(GCDTASK_BUFFER_MAX);
ssize_t bytesRead;
do
{
errno = 0;
bytesRead = read([stderrPipe fileHandleForReading].fileDescriptor, buffer, GCDTASK_BUFFER_MAX);
} while(bytesRead == -1 && errno == EINTR);
if(bytesRead > 0)
{
NSData* dataToPass = [NSData dataWithBytes:buffer length:bytesRead];
dispatch_async(dispatch_get_main_queue(), ^{
if(stdErr)
{
stdErr(dataToPass);
}
});
}
if(errno != 0 && bytesRead <= 0)
{
dispatch_source_cancel(_stderrSource);
}
free(buffer);
});
dispatch_resume(_stdoutSource);
dispatch_resume(_stderrSource);
executingTask.terminationHandler = ^(NSTask* task)
{
dispatch_source_cancel(_stdoutSource);
dispatch_source_cancel(_stderrSource);
if(exit)
exit();
};
[executingTask launch];
}
- (BOOL) WriteStringToStandardInput: (NSString*) input
{
return [self WriteDataToStandardInput:[input dataUsingEncoding:NSUTF8StringEncoding]];
}
/* Currently synchronous. TODO: Async fun! */
- (BOOL) WriteDataToStandardInput: (NSData*) input
{
if (!stdinPipe || stdinPipe == nil)
{
GCDDebug(@"Standard input pipe does not exist.");
return NO;
}
[[stdinPipe fileHandleForWriting] writeData:input];
return YES;
}
/* If you don't like setting your own array. You really should never have a use for this. */
- (void) AddArgument: (NSString*) argument
{
NSMutableArray* temp = [NSMutableArray arrayWithArray:_arguments];
[temp addObject:argument];
[self setArguments:temp];
}
- (void) RequestTermination
{
/* Ask nicely for SIGINT, then SIGTERM. */
[executingTask interrupt];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^(void)
{
[executingTask terminate];
});
}
@end