NSTask - 执行echo命令

时间:2012-05-30 16:12:54

标签: objective-c cocoa command nstask

我正在尝试运行一个简单的任务,该任务必须执行回声“Hello World”

这是我的代码:

NSTask *task;
    task = [[NSTask alloc] init];


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




    NSArray *arguments;

    arguments = [NSArray arrayWithObjects:@"echo","hello world" nil];
    [task setArguments: arguments];

    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    [task setStandardError: pipe];

    NSFileHandle *file;
    file = [pipe fileHandleForReading];



    [task launch];
    //...
    //Code to get task response

继续给我 没有这样的文件或目录错误 ..我做错了什么?

1 个答案:

答案 0 :(得分:3)

执行命令的正确方法是

bash -c "echo 'hello world'"

表示你应该传递的参数是

arguments = [NSArray arrayWithObjects:@"-c", @"echo 'hello world'", nil];