我正在使用SSH.NET库使用inotifywait命令在远程 linux 服务器上实现文件系统观察程序。本质上它是一个包装器:
ssh myhost "inotifywait -m -e close_write --format '%:e %f' /dropzone"
该命令将打印出来(到 STDOUT):
CLOSE_WRITE:CLOSE foo
CLOSE_WRITE:CLOSE bar
CLOSE_WRITE:CLOSE baz
这很简单,可以解析并转化为事件。无论如何,我的 C# 代码本质上是:
var privateKeyFile = new PrivateKeyFile(identity);
var client = new SshClient(hostname, username, privateKeyFile);
SshCommand command = null;
IAsyncResult result = null;
try
{
client.Connect();
command = client.CreateCommand("inotifywait -m -e close_write --format '%:e %f' " + dropZone);
result = command.BeginExecute();
Console.WriteLine("Watching for events");
var reader = new StreamReader(command.OutputStream);
string line = null;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
Console.WriteLine("Reached end of stream");
}
finally
{
if (client != null)
{
Console.WriteLine("Close the connection");
client.Dispose();
}
}
Console.WriteLine("Press enter to quit");
Console.ReadLine();
在写入单个文件后运行它会产生以下输出:
Watching for events
CLOSE_WRITE:CLOSE baz
Reached end of stream
Close the connection
Press enter to quit
立即出现Watching for events
并等待第一个文件被写入(阻塞等待,正如我所期望的那样StreamReader
)。但是,ReadLine
即使命令仍在愉快地运行,下一个而不是另一个阻塞等待返回 null (表示流结束)。我知道我可以这样改变循环:
while (!result.IsCompleted)
{
line = reader.ReadLine();
if (line != null)
{
Console.WriteLine(line);
}
}
结果是:
Watching for events
CLOSE_WRITE:CLOSE baz
CLOSE_WRITE:CLOSE bar
CLOSE_WRITE:CLOSE foo
...
根据需要,但它摆脱了对新输入的阻塞等待,这意味着循环不断旋转(显然是不希望的......)
你能解释一下这种行为吗?对另一种方法有什么建议吗?
- - 更新 - -
看起来该库正在迁移到 github 并进行更新。我已提交此问题以尝试解决此问题。