How can NSNotification be used to check a the status of an NSTask? I know there are a couple of class methods inside the NSTask but don't really understand how to implement them in a Cocoa application. Can somebody help me?
3 Answers
This blog post, Better way to read from an NSTask, describes how to use NSNotification
to recieve notifications from an NSTask
.
If you know that your task is not long-running, there is a simpler solution. My answer to another SO question, Execute a terminal command from a Cocoa app, has an example of using NSTask
that includes returning the status of the task w/o NSNotification

- 1
- 1

- 26,244
- 11
- 57
- 60
Thanks Gordon, I have tried out the solution you gave but what's confusing me is when I write the code:
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
What is the output data can be return from the task?for my case the console window jus get stuck there and nothing have returned

- 486
- 1
- 7
- 30
Task will be stuck when you won't read what it is sending on stdout/stderr. That's why you need to create pipes and set them using setStandardOutput
.
Use [NSFileHandle readToEndOfFileInBackgroundAndNotify]
and wait for NSFileHandleReadToEndOfFileCompletionNotification
. It will give you all data in the callback.

- 97,764
- 37
- 219
- 309