-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSSYTasker.m
356 lines (292 loc) · 12.6 KB
/
SSYTasker.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
#import "SSYTasker.h"
#import <pthread.h>
#import "SSYRunLoopTickler.h"
NSString* constKeySSYTaskerFileHandle = @"fileHandle" ;
NSString* constKeySSYTaskerData = @"data" ;
NSString* SSYTaskerErrorDomain = @"SSYTaskerErrorDomain" ;
NSInteger SSYTaskerMetaErrorCode = 444000 ;
@interface SSYTasker ()
@property (assign) FILE * restrict heartbeatTo ;
@end
@implementation NSFileHandle (CSFileHandleExtensions)
- (NSData*)availableDataError_p:(NSError**)error_p {
while (YES) {
@try {
return [self availableData] ;
}
@catch (NSException *exception) {
if (
[[exception name] isEqualToString:NSFileHandleOperationException]
&&
[[exception reason] isEqualToString:@"*** -[NSConcreteFileHandle availableData]: Interrupted system call"]
) {
// This exception was raised by the NSTask Stealth Bug and should be ignored
}
else {
// This is a real exception which we need to handle
if (error_p) {
NSMutableDictionary* exceptionInfo = [[NSMutableDictionary alloc] init] ;
id value ;
value = [exception name] ;
if (value) {
[exceptionInfo setObject:value
forKey:@"Name"] ;
}
value = [exception reason] ;
if (value) {
[exceptionInfo setObject:value
forKey:@"Reason"] ;
}
value = [exception userInfo] ;
if (value) {
[exceptionInfo setObject:value
forKey:@"User Info"] ;
}
NSString* errorDesc = @"Error occurred while reading" ;
*error_p = [NSError errorWithDomain:SSYTaskerErrorDomain
code:SSYTaskerErrorCodeExceptionOccurredWhileReading
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
errorDesc, NSLocalizedDescriptionKey,
[NSDictionary dictionaryWithDictionary:exceptionInfo], @"Underlying Exception",
nil]] ;
}
else {
// We cannot handle this exception because caller did not
// provide a pointer for returning errors.
@throw ;
}
return nil ;
}
}
}
}
@end
void* writeDataToHandle(NSDictionary*info) {
NSFileHandle* fileHandle = [info objectForKey:constKeySSYTaskerFileHandle] ;
NSData* data = [info objectForKey:constKeySSYTaskerData] ;
[fileHandle writeData:data] ;
[fileHandle closeFile] ;
return nil ;
}
@interface SSYTasker ()
@property BOOL isTaskDone ;
@property NSMutableData* stdoutData ;
@property NSMutableData* stderrData ;
@property NSError* error ;
@end
@implementation SSYTasker
@synthesize isTaskDone = m_isTaskDone ;
@synthesize stdoutData = m_stdoutData ;
@synthesize stderrData = m_stderrData ;
@synthesize error = m_error ;
@synthesize delegate = m_delegate ;
- (void)eatFromFilehandle:(NSFileHandle*)fileHandle
pipeName:(NSString*)pipeName
intoData:(NSMutableData *)mutableData {
NSError* error = nil ;
NSData* data = [fileHandle availableDataError_p:&error] ;
if (error) {
[self setError:error] ;
}
if (pipeName) {
[[self delegate] gotBytesCount:[data length]
pipeName:pipeName] ;
}
if ([data length] > 0) {
[mutableData appendData:data] ;
// Tell the fileHandle that we want more data.
[fileHandle waitForDataInBackgroundAndNotify] ;
}
else {
// According to documentation, it tells us that either stdout or stderr
// is done. In my experience, this branch usually does not execute
// in a typical program run. But somtimes it does. We ignore it and
// wait instead for NSTaskDidTerminateNotification which is reliable.
}
}
- (void)eatStdoutFromFileHandle:(NSFileHandle *)fileHandle {
NSMutableData* mutableData = [self stdoutData] ;
if (!mutableData) {
mutableData = [[NSMutableData alloc] init] ;
[self setStdoutData:mutableData] ;
}
[self eatFromFilehandle:fileHandle
pipeName:@"stdout"
intoData:mutableData] ;
}
- (void)eatStdoutNote:(NSNotification*)note {
NSFileHandle* fileHandle = [note object] ;
[self eatStdoutFromFileHandle:fileHandle] ;
}
- (void)eatStderrFromFileHandle:(NSFileHandle *)fileHandle {
NSMutableData* mutableData = [self stderrData] ;
if (!mutableData) {
mutableData = [[NSMutableData alloc] init] ;
[self setStderrData:mutableData] ;
}
[self eatFromFilehandle:fileHandle
pipeName:@"stderr"
intoData:mutableData];
}
- (void)eatStderrNote:(NSNotification*)note {
NSFileHandle* fileHandle = [note object] ;
[self eatStderrFromFileHandle:fileHandle];
}
- (void)taskTerminatedNote:(NSNotification*)note {
[[NSNotificationCenter defaultCenter] removeObserver:self] ;
[self setIsTaskDone:YES] ;
}
- (void)kickFromTimer:(NSTimer*)timer {
FILE * restrict heartbeatTo = [self heartbeatTo] ;
if (heartbeatTo != NULL) {
fprintf(heartbeatTo, "H") ;
}
[SSYRunLoopTickler tickle] ;
}
- (NSInteger)runCommand:(NSString*)launchPath
arguments:(NSArray*)arguments
heartbeatTo:(FILE *restrict)heartbeatTo
stdinData:(NSData*)stdinData
workingIn:(NSString*)workingDirectory {
NSInteger errorCode = 0 ;
// Reset in case we are invoked more than once in a lifetime.
[self setIsTaskDone:NO] ;
[self setStdoutData:nil] ;
[self setStderrData:nil] ;
[self setError:nil] ;
[self setHeartbeatTo:heartbeatTo] ;
// Create task with given parameters
NSTask *task = [[NSTask alloc] init] ;
[task setLaunchPath:launchPath] ;
if (arguments) {
[task setArguments:arguments] ;
}
if (workingDirectory) {
[task setCurrentDirectoryPath:workingDirectory] ;
}
NSFileHandle* fileStdin = nil ;
if (stdinData) {
NSPipe *pipeStdin = [NSPipe pipe] ;
fileStdin = [pipeStdin fileHandleForWriting] ;
[task setStandardInput:pipeStdin] ;
}
/*
In order to prevent the stdout and stderr pipes from clogging and stalling
tasks that return a lot of stdout or stderr, instead of invoking
-[NSTask waitUntilExit], we create a run loop, observe when data is
available in either pipe and process it out. To terminate, we watch for
NSTaskDidTerminateNotification.
*/
// Prepare to receive stdout
NSPipe *pipeStdout = [[NSPipe alloc] init] ;
NSFileHandle *fileStdout = [pipeStdout fileHandleForReading] ;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(eatStdoutNote:)
name:NSFileHandleDataAvailableNotification
object:fileStdout] ;
[task setStandardOutput:pipeStdout] ;
[fileStdout waitForDataInBackgroundAndNotify] ;
// Prepare to receive stderr
NSPipe *pipeStderr = [[NSPipe alloc] init] ;
NSFileHandle *fileStderr = [pipeStderr fileHandleForReading];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(eatStderrNote:)
name:NSFileHandleDataAvailableNotification
object:fileStderr] ;
[task setStandardError:pipeStderr] ;
[fileStderr waitForDataInBackgroundAndNotify] ;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(taskTerminatedNote:)
name:NSTaskDidTerminateNotification
object:task] ;
[task launch] ;
if (stdinData) {
// Torsten Curdt says that we need to write to stdin in a separate
// thread, in case it is more than 64 KB. I don't know if that is
// still true, but we use his code here, updated for ARC, with
// improved error handling.
pthread_t thread = nil ;
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
fileStdin, constKeySSYTaskerFileHandle,
stdinData, constKeySSYTaskerData,
nil] ;
int err ;
err = pthread_create(
&thread,
nil,
(void *(*)(void *))writeDataToHandle,
(__bridge void *)info) ;
if (err != 0) {
errorCode = SSYTaskerErrorCodeCouldNotCreateThreadForStdin ;
}
if (errorCode == 0) {
err = pthread_detach(thread) ;
if (err != 0) {
errorCode = SSYTaskerErrorCodeCouldNotDetachThreadForStdin ;
}
}
}
int exitStatus = -1 ;
if (errorCode == 0) {
NSRunLoop *runLoop = [NSRunLoop currentRunLoop] ;
NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(kickFromTimer:)
userInfo:nil
repeats:YES] ;
do {
@autoreleasepool {
BOOL keepRunning = [runLoop runMode:NSDefaultRunLoopMode
beforeDate:[NSDate distantFuture]] ;
if (!keepRunning) {
[self setIsTaskDone:YES] ;
}
// That's all. Actual work is done by notification handlers.
// Just run the loop again, to wait for next notification or done.
}
} while ([self isTaskDone] == NO) ;
[timer invalidate] ;
exitStatus = [task terminationStatus] ;
// Added the following to fix bug, 20130712, which caused stderr or
// stdout to be not returned about 0.5% of the time. Apparently there
// is some kind of race condition wherein an NSTask can terminate
// before the final notification of available stdout or stderr has
// been processed, or something like that. Anyhow, it took me two days
// to figure this out. This fixed it…
[self eatStdoutFromFileHandle:fileStdout] ;
[self eatStderrFromFileHandle:fileStderr] ;
[[NSNotificationCenter defaultCenter] removeObserver:self] ;
}
if ((errorCode != 0) && ([self error] == nil)) {
NSError* error = [NSError errorWithDomain:SSYTaskerErrorDomain
code:errorCode
userInfo:nil] ;
[self setError:error] ;
}
NSInteger result = [self error] ? SSYTaskerMetaErrorCode : exitStatus ;
return result ;
}
- (NSData*)stdoutFromLastRun {
return [[self stdoutData] copy] ;
}
- (NSData*)stderrFromLastRun {
return [[self stderrData] copy] ;
}
- (NSError*)errorFromLastRun {
NSError* error = [self error] ;
if (!error) {
if (errno) {
NSString* desc = [NSString stringWithFormat:
@"Command returned Unix errno %d",
errno] ;
error = [NSError errorWithDomain:SSYTaskerErrorDomain
code:SSYTaskerErrorCodeUnixCommandError
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
desc, NSLocalizedDescriptionKey,
[NSNumber numberWithInt:errno], @"errno",
nil]] ;
}
}
return error ;
}
@end