forked from jerrykrinock/CategoriesObjC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSFileManager+SSYFileDescriptor.m
99 lines (86 loc) · 2.81 KB
/
NSFileManager+SSYFileDescriptor.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
#import "NSFileManager+SSYFileDescriptor.h"
#import "SSYShellTasker.h"
NSString* const SSYFileManagerFileDescriptorErrorDomain = @"SSYFileManagerFileDescriptorErrorDomain" ;
@implementation NSFileManager (SSYFileDescriptor)
+ (NSString*)pathForFileDescriptor:(NSInteger)fileDescriptor
pid:(pid_t)pid
error_p:(NSError**)error_p {
if (!pid) {
pid = [[NSProcessInfo processInfo] processIdentifier] ;
}
NSData* stdoutData = nil ;
NSData* stderrData = nil ;
NSError* error = nil ;
NSInteger result = [SSYShellTasker doShellTaskCommand:@"/usr/sbin/lsof"
arguments:[NSArray arrayWithObjects:
@"-Fn", // output only the process 'name' (n)
@"-w", // suppress warnings
@"-a", // logical-AND the next two arguments
[NSString stringWithFormat:@"-p%d", pid],
[NSString stringWithFormat:@"-d%d", fileDescriptor],
nil]
inDirectory:nil
stdinData:nil
stdoutData_p:&stdoutData
stderrData_p:&stderrData
timeout:5.0
error_p:&error] ;
NSMutableDictionary* errorInfo = [[NSMutableDictionary alloc] init] ;
NSInteger errorCode = 0 ;
NSString* path = nil ;
if (result == 0) {
if (stdoutData) {
NSString* lsofOutput = [[NSString alloc] initWithData:stdoutData
encoding:NSUTF8StringEncoding] ;
if (lsofOutput) {
// lsofOutput will be two lines, like this:
// p<pid>
// n</path/we/want>
NSArray* lsofLines = [lsofOutput componentsSeparatedByString:@"\n"] ;
for (NSString* line in lsofLines) {
if ([line hasPrefix:@"n"] && [line length] > 1) {
path = [line substringFromIndex:1] ;
break ;
}
}
if (!path) {
errorCode = 647701 ;
[errorInfo setObject:lsofLines
forKey:@"Lines"] ;
}
}
else {
errorCode = 644702 ;
[errorInfo setObject:stdoutData
forKey:@"Stdout"] ;
}
[lsofOutput release] ;
}
else {
errorCode = 644703 ;
}
}
else {
errorCode = 644704 ;
[errorInfo setObject:[NSNumber numberWithInteger:result]
forKey:@"Cmd Result"] ;
[errorInfo setValue:error
forKey:NSUnderlyingErrorKey] ;
}
if (error_p && (errorCode != 0)) {
[errorInfo setObject:@"Could not get path"
forKey:NSLocalizedDescriptionKey] ;
[errorInfo setObject:[NSNumber numberWithInteger:pid]
forKey:@"Pid"] ;
[errorInfo setObject:[NSNumber numberWithInteger:fileDescriptor]
forKey:@"FD"] ;
[errorInfo setValue:[[[NSString alloc] initWithData:stderrData
encoding:NSASCIIStringEncoding] autorelease]
forKey:@"Stderr"] ;
*error_p = [NSError errorWithDomain:SSYFileManagerFileDescriptorErrorDomain
code:errorCode
userInfo:errorInfo] ;
}
return path ;
}
@end