简体   繁体   中英

Keep a NSTask Session Running - Cocoa

I run a simple grep command in my Cocoa app like so:

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/grep"];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"foo", @"bar.txt", nil];
[task setArguments: arguments];

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

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];

NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"grep returned:\n%@", string);

[string release];
[task release];

However, I am somewhat curious to know how commands entered through terminal, which don't give out an output and are not executed promptly unless exited with something like Control + C can be run with this technique. Something like running java -jar server.jar where it keeps running until quit out of the session. How would I do something like that where the session is not automatically ended once the command has been launched?

Would I just need to comment out the part where it releases the NSTask ? Any suggestions would be nice!

When using NSTask with an underlying program that doesn't exit immediately:

  1. You shouldn't use -[NSFileHandle readDataToEndOfFile] since there is no end of file. Instead, you should use -[NSFileHandle readInBackgroundAndNotify] to read the standard output pipe of that task in the background, and be notified when data is available;

  2. You should use -[NSTask release] only when you've determined that the task shouldn't run any more. In that case, prior to releasing the task, you should send its standard input the command that causes the underlying program to exit (eg the characters equivalent to control - d ), or send it -terminate or -interrupt .

  3. You shouldn't use -waitUntilExit unless you've spawned a secondary thread to deal with that task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM