Как выполнить команду оболочки «ping» и получить результат в строку в Objective-C / Cocoa? - PullRequest
0 голосов
/ 22 октября 2011

Я попробовал этот код

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 Ответ

2 голосов
/ 22 октября 2011

Попробуйте заменить:

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

с

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

, поскольку там находится пинг.

...