运行命令行工具时的NSTask和参数

时间:2011-12-03 00:29:04

标签: cocoa nstask

如何在此代码中将参数(本例中为host)传递给NSTask?它不接受主机NSString。如果我通过ping传递主机值,例如..

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

然后它的工作原理。但它不会单独采用主持人的论点。感谢您的帮助。

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 个答案:

答案 0 :(得分:5)

使用stringWithFormat

NSString方法
 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];

答案 1 :(得分:1)

你的论点不正确。首先,您应该将启动路径设置为/ bin / ping,或者任务所在的位置,然后参数应该是您通常在命令行中输入的参数的数组,但是那里的空间分开..

有关如何正确执行此操作的详细信息,请查看本教程Wrapping UNIX commands

答案 2 :(得分:0)

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

Bash -c需要在引号中使用您的命令。

相关问题