2

How would I pass arguments (host in this case) to NSTask in this code? It does not accept the host NSString. If I pass the host value with the ping, for e.g..

[NSArray arrayWithObjects:@"-c",@"ping -c 5 www.google.com",nil]

then it works. But it won't take the host argument separately. Thanks for the help in advance.

task =  [[NSTask alloc] init];
[pipe release];
pipe = [[NSPipe alloc] init];
[task setStandardInput: [NSPipe pipe]];  

[task setLaunchPath:@"/bin/bash"];

NSArray *args = [NSArray arrayWithObjects:@"-c",@"ping -c 5",host,nil];

[task setArguments:args];
[task setStandardOutput:pipe];
NSFileHandle *fh = [pipe fileHandleForReading];

3 Answers 3

6

Use stringWithFormat method of NSString class

 task =  [[NSTask alloc] init];
        [pipe release];
        pipe = [[NSPipe alloc] init];
        [task setStandardInput: [NSPipe pipe]];  

    [task setLaunchPath:@"path"];

    NSArray *args = [NSArray arrayWithObjects:@"-c",[NSString stringWithFormat: @"%@ %@ %@ %@",@"ping",@"-c",@"5",host],nil];

    [task setArguments:args];
    [task setStandardOutput:pipe];
    NSFileHandle *fh = [pipe fileHandleForReading];
0
1

Your arguments are not correct. First of all, you should set the launchpath to /bin/ping, or wherever the task is located, then the arguments should be an array of the arguments you would normally enter on the command line, but then seperated by spaces there..

Please take a look at this tutorial Wrapping UNIX commands for more information on how to do this properly.

0
NSMutableArray *args = [NSMutableArray array];
NSArray *args = [NSArray arrayWithObjects:@"-c", @"\"ping -c 5", host, @"\"",nil]
[task setArguments:args];

Bash -c needs to take your command in quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.