使用 D 控制交互过程
Control an interactive process using D
我有一个程序等待一行标准输入,然后在处理它之后(这需要相对较长的时间)发出一个答案。该程序将接受输入,直到输入流关闭。
我如何从 D 控制该程序?也就是说我怎么能
- 给子进程一行标准输入。
- 等待子进程回答。
- 重复,直到我用尽我想给它的输入。
我尝试了以下代码,但毫不奇怪,它等待子进程完全完成,然后一次打印所有输出:
module main;
import std.file;
import std.path;
import std.process;
import std.stdio;
void main(string[] args)
{
string[] inputs = ["test string 1", "test string 2"];
auto pipes = pipeProcess(buildPath(getcwd(), "LittleTextProcessingApp"), Redirect.all);
scope(exit) wait(pipes.pid);
foreach(input; inputs)
{
pipes.stdin.writeln(input);
}
pipes.stdin.close;
foreach(line; pipes.stdout.byLine)
{
writeln(line);
}
}
也就是说,它在延迟一秒后打印,
The following was input 500 ms ago: test string 1
The following was input 500 ms ago: test string 2
期望的行为是打印
The following was input 500 ms ago: test string 1
半秒后,500 毫秒后第二行。
我作为子进程测试的程序源码如下:
module main;
import std.stdio;
import core.thread;
void main(string[] args)
{
foreach(input; stdin.byLine)
{
auto duration = 500.msecs;
stderr.writefln("Doing something for %s....", duration);
Thread.sleep(duration);
writefln("The following was input %s ago: %s", duration, input);
}
}
罪魁祸首是子进程。
在writefln
之后,默认不刷新输出。
相反,它保存在缓冲区中(几千字节长)。
这是一种常用技术(不特定于 D),可以大大提高速度,例如,将大文件写入大量 few-byte 块的 HDD。
要刷新缓冲区,请在每次希望输出立即出现时使用 stdout.flush()
。
在子示例代码中的最后一个 writefln
之后添加该行可修复示例中的情况。
我有一个程序等待一行标准输入,然后在处理它之后(这需要相对较长的时间)发出一个答案。该程序将接受输入,直到输入流关闭。
我如何从 D 控制该程序?也就是说我怎么能
- 给子进程一行标准输入。
- 等待子进程回答。
- 重复,直到我用尽我想给它的输入。
我尝试了以下代码,但毫不奇怪,它等待子进程完全完成,然后一次打印所有输出:
module main;
import std.file;
import std.path;
import std.process;
import std.stdio;
void main(string[] args)
{
string[] inputs = ["test string 1", "test string 2"];
auto pipes = pipeProcess(buildPath(getcwd(), "LittleTextProcessingApp"), Redirect.all);
scope(exit) wait(pipes.pid);
foreach(input; inputs)
{
pipes.stdin.writeln(input);
}
pipes.stdin.close;
foreach(line; pipes.stdout.byLine)
{
writeln(line);
}
}
也就是说,它在延迟一秒后打印,
The following was input 500 ms ago: test string 1
The following was input 500 ms ago: test string 2
期望的行为是打印
The following was input 500 ms ago: test string 1
半秒后,500 毫秒后第二行。
我作为子进程测试的程序源码如下:
module main;
import std.stdio;
import core.thread;
void main(string[] args)
{
foreach(input; stdin.byLine)
{
auto duration = 500.msecs;
stderr.writefln("Doing something for %s....", duration);
Thread.sleep(duration);
writefln("The following was input %s ago: %s", duration, input);
}
}
罪魁祸首是子进程。
在writefln
之后,默认不刷新输出。
相反,它保存在缓冲区中(几千字节长)。
这是一种常用技术(不特定于 D),可以大大提高速度,例如,将大文件写入大量 few-byte 块的 HDD。
要刷新缓冲区,请在每次希望输出立即出现时使用 stdout.flush()
。
在子示例代码中的最后一个 writefln
之后添加该行可修复示例中的情况。