如何在Objective-C / Cocoa中执行shell命令“ping”并将结果输入到字符串中?

时间:2011-10-21 22:29:39

标签: cocoa shell task ping nstask

我试过这段代码

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/ping"];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"-c", @"3",@"stackoverfow.com", nil];
[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];

NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"ping returned:\n%@", string);

[string release];
[task release];

得到了这个

2011-10-21 17:34:42.805 pintTest[8819:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'launch path not accessible'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff8acab286 __exceptionPreprocess + 198
    1   libobjc.A.dylib                     0x00007fff89463d5e objc_exception_throw + 43
    2   CoreFoundation                      0x00007fff8acab0ba +[NSException raise:format:arguments:] + 106
    3   CoreFoundation                      0x00007fff8acab044 +[NSException raise:format:] + 116
    4   Foundation                          0x00007fff8fc6c2c8 -[NSConcreteTask launchWithDictionary:] + 470
    5   pintTest                            0x0000000100000de0 main + 400
    6   pintTest                            0x0000000100000c44 start + 52
    7   ???                                 0x0000000000000001 0x0 + 1
)
terminate called throwing an exceptionsharedlibrary apply-load-rules all
Current language:  auto; currently objective-c

1 个答案:

答案 0 :(得分:2)

尝试更换:

[task setLaunchPath: @"/usr/bin/ping"];

[task setLaunchPath: @"/sbin/ping"];

因为那是ping所在的位置。