[英]Keep a NSTask Session Running - Cocoa
I run a simple grep command in my Cocoa app like so:我在我的 Cocoa 应用程序中运行一个简单的 grep 命令,如下所示:
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.但是,我有点想知道如何通过终端输入命令,这些命令不会发出 output 并且不会立即执行,除非使用Control + C之类的东西退出可以使用这种技术运行。 Something like running
java -jar server.jar
where it keeps running until quit out of the session.像运行
java -jar server.jar
这样它会一直运行直到退出 session。 How would I do something like that where the session is not automatically ended once the command has been launched?一旦命令启动,session 不会自动结束,我该怎么做?
Would I just need to comment out the part where it releases the NSTask
?我只需要注释掉它发布
NSTask
的部分吗? Any suggestions would be nice!任何建议都会很好!
When using NSTask
with an underlying program that doesn't exit immediately:将
NSTask
与不会立即退出的底层程序一起使用时:
You shouldn't use -[NSFileHandle readDataToEndOfFile]
since there is no end of file.你不应该使用
-[NSFileHandle readDataToEndOfFile]
因为没有文件结尾。 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;相反,您应该使用
-[NSFileHandle readInBackgroundAndNotify]
在后台读取该任务的标准 output pipe,并在数据可用时收到通知;
You should use -[NSTask release]
only when you've determined that the task shouldn't run any more.仅当您确定该任务不应再运行时,才应使用
-[NSTask release]
。 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
.在这种情况下,在发布任务之前,您应该向其标准输入发送导致底层程序退出的命令(例如相当于control -d的字符),或者发送它
-terminate
或-interrupt
。
You shouldn't use -waitUntilExit
unless you've spawned a secondary thread to deal with that task.除非您已生成辅助线程来处理该任务,否则您不应使用
-waitUntilExit
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.