1

I created a command-line application for Mac OS without the GUI. This application is located at /usr/local/bin. And in some cases I need to execute Apple Script within that application. To do this, I create an NSTask and trying to run the following command:

NSTask *createTask = [[NSTask alloc] init];
    createTask.launchPath = @"/bin/bash";
    NSString *showAlert = [NSString stringWithFormat:@"/usr/bin/osascript -e 'tell application \"Finder\" to display alert \"My text.\"'"];
    NSArray *arguments = [NSArray arrayWithObjects:@"-c",showAlert, nil];
    createTask.arguments = arguments;
[createTask launch];

After it runs, nothing happens, only in logs appear the message:

Apr 14 15:35:15 Mac-mini kernel[0]: my-app: guarded fd exception: fd 0 code 0x2 guard 0x7fff8b9e12a8
Apr 14 15:35:15 Mac-mini com.apple.xpc.launchd[1] (com.apple.ReportCrash.Root[26852]): Endpoint has been activated through legacy launch(3) APIs. Please switch to XPC or bootstrap_check_in(): com.apple.ReportCrash.DirectoryService
Apr 14 15:35:15 Mac-mini diagnosticd[16097]: error evaluating process info - pid: 26851, punique: 26851
Apr 14 15:35:16 Mac-mini sandboxd[16099] ([26851]): my-app(26851) deny file-read-data /

But if you run this command directly from terminal, it is executed correctly. Please tell me, what am I doing wrong?

Emmett
  • 464
  • 5
  • 11
  • I have an inkling that `NSTask` would use the run-loop. How are you managing the run-loop in your program? – trojanfoe Apr 14 '16 at 10:42
  • It seems i not using run-loop management. Can you suggest that I should try? – Emmett Apr 14 '16 at 10:51
  • I don't think it actually relates to your problem, however if you are using the Foundation framework then you do need a run-loop for much of it. I have a simple [RunLoopController](https://github.com/trojanfoe/RunLoopController) for use on the command line, which you might find helpful. – trojanfoe Apr 14 '16 at 10:53

1 Answers1

0

I think the issue may be with your use of quotes. When I try and manually run the same command in the shell with your quoting style, it won't work. My examples below do work. Can you switch your single and double quotes? Encase your initial call with single quotes and then use the double quote around the osascript? Also, there is no need to use the tell application \"Finder\" to as display alert is not part of the Finder dictionary.

You have...

/usr/bin/osascript -e 'tell application \"Finder\" to display alert \"My text.\"'

Try changing it to...

/usr/bin/osascript -e "display alert \"My text.\""

Or an even simpler version...

osascript -e "display alert \"My text.\""
ThrowBackDewd
  • 1,737
  • 2
  • 13
  • 16
  • I think the problem is not in the syntax. Because if I run my commnd-line application from the terminal then everything works fine. But in this case my command-line application is invoked by another application (driver) is not from the main thread. – Emmett Apr 15 '16 at 06:13