Dru*_*erB 7 macos cocoa objective-c nstask nspipe
我正在尝试使用NSTask运行一个简单的bash脚本并将输出定向到文本视图.执行任务后,我的应用程序的CPU使用率为100%,即使它很简单echo
(暂时).
我创建了一个全新的项目来隔离问题:
@interface AppDelegate ()
@property (nonatomic) NSTask *task;
@property (nonatomic) NSPipe *pipe;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
self.pipe = [NSPipe pipe];
self.pipe.fileHandleForReading.readabilityHandler = ^(NSFileHandle *h) {
NSLog(@"Read: %@", [h readDataToEndOfFile]);
};
self.task = [[NSTask alloc] init];
self.task.launchPath = @"/bin/bash";
self.task.arguments = @[@"-c", @"echo test"];
self.task.standardOutput = self.pipe;
[self.task launch];
}
@end
Run Code Online (Sandbox Code Playgroud)
它被正确执行并输出(作为NSData
)记录NSLog
:
PipeTest[3933:2623] Read: <74657374 0a>
Run Code Online (Sandbox Code Playgroud)
但是,在我终止我的应用程序之前,CPU使用率保持在100%.
编辑:
Time Profiler测试返回下面的列表,但我不知道如何解释这个.
Flu*_*imp 10
文件句柄是否打开?
@interface AppDelegate ()
@property (nonatomic) NSTask *task;
@property (nonatomic) NSPipe *pipe;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
self.pipe = [NSPipe pipe];
self.pipe.fileHandleForReading.readabilityHandler = ^(NSFileHandle *h) {
NSLog(@"Read: %@", [h readDataToEndOfFile]);
[h closeFile];
};
self.task = [[NSTask alloc] init];
self.task.launchPath = @"/bin/bash";
self.task.arguments = @[@"-c", @"echo test"];
self.task.standardOutput = self.pipe;
[self.task launch];
}
Run Code Online (Sandbox Code Playgroud)
关闭文件NSFileHandle
h
似乎会使您的CPU使用率恢复正常.
归档时间: |
|
查看次数: |
1230 次 |
最近记录: |