如何读写NSTask

时间:2013-01-18 21:08:26

标签: objective-c pipe nstask

我有它的工作。但是,最初它似乎在等待输入。如何在停止并等待输入之前读取输出内容?

task starts
stdout should post data for "sftp> " but nothing happens, its waiting for input
If I write "\n" to stdin
stdout notifies me of data available which ends up being "sftp> \n"

以下是它的实施方式:

[self.task = [[NSTask alloc] init];
[self.task setLaunchPath:executablePath];
[self.task setArguments: args];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(terminatedNotification:) name:NSTaskDidTerminateNotification object:self.task];

//reading
self.stdoutPipe = [NSPipe pipe];
self.task.standardOutput = self.stdoutPipe;
[self.stdoutPipe.fileHandleForReading waitForDataInBackgroundAndNotify];

//error
self.stderrorPipe = [NSPipe pipe];
self.task.standardError = self.stderrorPipe;
[self.stderrorPipe.fileHandleForReading waitForDataInBackgroundAndNotify];

/*
reading works perfect until I uncomment this section
//writing
self.stdinPipe = [NSPipe pipe];
self.task.standardInput = self.stdinPipe;
*/

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataAvailable:) name:NSFileHandleDataAvailableNotification object:self.stdoutPipe.fileHandleForReading];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataAvailable:) name:NSFileHandleDataAvailableNotification object:self.stderrorPipe.fileHandleForReading];

1 个答案:

答案 0 :(得分:3)

写入NSFileHandle的数据被缓冲。只有在刷新缓冲区后,它才能在管道的另一端读取。如果

,则刷新缓冲区
  1. 它已满,不再有数据适合它。
  2. 写入换行符(“\ n”)(autoflush)。
  3. 通过调用- (void)synchronizeFile
  4. 明确刷新它