Getting exit status after starting the application with running NSWorkspaceApplicationAtURL

I am somehow new to Mac programming. I port the plugin to OSX. I need an application to launch the second application (which I do not control the source), and then get its exit code. NSWorkspace launchApplicationAtURL works great to launch it with the necessary arguments, but I don't see how to get the exit code. Is there a way to get it after setting up a notification about the termination of the second application? I see tools for getting exit code using NSTask. Should I use this?

+3
source share
2 answers

Methods are NSWorkspacereally designed to run independent applications; use NSTaskto "run another program as a subprocess and ... control the execution of programs" according to the documents.

Here is an easy way to run the executable and return to its standard output - it blocks waiting for completion:

// Arguments:
//    atPath: full pathname of executable
//    arguments: array of arguments to pass, or nil if none
// Return:
//    the standard output, or nil if any error
+ (NSString *) runCommand:(NSString *)atPath withArguments:(NSArray *)arguments
{
    NSTask *task = [NSTask new];
    NSPipe *pipe = [NSPipe new];

    [task setStandardOutput:pipe];     // pipe standard output

    [task setLaunchPath:atPath];       // set path
    if(arguments != nil)
        [task setArguments:arguments]; // set arguments

    [task launch];                     // execute

    NSData *data = [[pipe fileHandleForReading] readDataToEndOfFile]; // read standard output

    [task waitUntilExit];              // wait for completion

    if ([task terminationStatus] != 0) // check termination status
        return nil;

    if (data == nil)
        return nil;

    return [NSString stringWithUTF8Data:data]; // return stdout as string
}

You may not want to block, especially if this is your main UI thread, put standard input, etc.

+6
source

In fact, this NSTask property should do the trick: terminalStatus

From Apple doc:

Returns the exit status returned by the recipient executable.

  • (integer) terminationStatus

, . , , .

if (![aTask isRunning]) {
    int status = [aTask terminationStatus];
    if (status == ATASK_SUCCESS_VALUE)
        NSLog(@"Task succeeded.");
    else
        NSLog(@"Task failed.");
}

, .

+1

All Articles