Getting exit status after launching app with NSWorkspace launchApplicationAtURL

假装没事ソ 提交于 2021-01-27 13:26:49

问题


I'm kind of new at Mac programming. I am porting a plugin to OSX. I need my application to launch a second app (which I do not control the source for) and then get its exit code. NSWorkspace launchApplicationAtURL works great to launch it with the needed arguments but I can't see how to get the exit code. Is there a way to get it after setting up notification for termination of the second app? I see tools for getting an exit code using NSTask instead. Should I be using that?


回答1:


The NSWorkspace methods are really for launching independent applications; use NSTask to "run another program as a subprocess and ... monitor that program’s execution" as per the docs.

Here is a simple method to launch an executable and return 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, supply standard input etc.




回答2:


In fact, this property of the NSTask should do the trick: terminationStatus

From Apple's doc:

Returns the exit status returned by the receiver’s executable.

  • (int)terminationStatus

I tested it and it works ok. Watch out to test if the task is running first, otherwise an exception will be launched.

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

Hope it helps.



来源:https://stackoverflow.com/questions/5302599/getting-exit-status-after-launching-app-with-nsworkspace-launchapplicationaturl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!