cocoanstask

NSTask and arguments when running command line tools


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];

Solution

  • 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];