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

Zio*_*ing 2 cocoa nstask

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

[NSArray arrayWithObjects:@"-c",@"ping -c 5 www.google.com",nil]
Run Code Online (Sandbox Code Playgroud)

然后它工作.但它不会单独采用主持人的论点.我在这里先向您的帮助表示感谢.

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];
Run Code Online (Sandbox Code Playgroud)

Par*_*fna 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];
Run Code Online (Sandbox Code Playgroud)