objective-c中调用shell命令

Launching a task [permalink]

Here are the basics to launch "ls -l -a -t" in the current directory, and then read the result into an NSString:


NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/ls"];

    NSArray *arguments;
    arguments = [NSArray arrayWithObjects: @"-l", @"-a", @"-t", nil];
    [task setArguments: arguments];

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

    NSFileHandle *file;
    file = [pipe fileHandleForReading];

    [task launch];

    NSData *data;
    data = [file readDataToEndOfFile];

    NSString *string;
    string = [[NSString alloc] initWithData: data
                               encoding: NSUTF8StringEncoding];
    NSLog (@"woop!  got\n%@", string);

Performing complex pipelines. [permalink]
You can create multiple NSTasks and a bunch of NSPipes and hook them together, or you can use the "sh -c" trick to feed a shell a command, and let it parse it and set up all the IPC. This pipeline cats /usr/share/dict/words, finds all the words with 'ham' in them, reverses them, and shows you the last 5.  

NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/sh"];

    NSArray *arguments;
    arguments = [NSArray arrayWithObjects: @"-c",
                         @"cat /usr/share/dict/words | grep -i ham | rev | tail -5", nil];
    [task setArguments: arguments];
    // and then do all the other jazz for running an NSTask.


http://borkware.com/quickies/one?topic=nstask

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值