Friday, September 7, 2012

Execute a terminal command on a Cocoa application

* refer to

In order to write an cocoa application that can start/stop webserver embedded within, I needed some method could run terminal commands. One user(thanks kent!) suggested to use /bin/sh to run shell script file – and you might know, /bin/sh utility can run a line of command instead of script file with –c option. With NSTask and /bin/sh, I made some method to run a shell command by line:
NSString *runCommand(NSString *commandToRun)
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/sh"];

    NSArray *arguments = [NSArray arrayWithObjects:
                          @"-c" ,
                          [NSString stringWithFormat:@"%@", commandToRun],
    NSLog(@"run command: %@",commandToRun);
    [task setArguments: arguments];

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

    NSFileHandle *file;
    file = [pipe fileHandleForReading];

    [task launch];

    NSData *data;
    data = [file readDataToEndOfFile];

    NSString *output;
    output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    return output;

Using above method, you can write a code to run a line of terminal shell command like this:

NSString *output = runCommand(@"ps -A | grep mysql");