如何保持通往另一个进程的管道打开

How to keep the pipe to another process opened

我正在尝试通过 pipesbc 实例通信,但使用我的代码它每次都运行新实例。是否有可能在我关闭连接之前一直保持连接?

:- use_module(library(unix)).
:- use_module(library(process)).

read_result(Out, Result) :-
     read(Out, Result).

send_command(R, Command, Result) :-
     write(R.in, Command),
     nl(R.in),
     flush_output(R.in),
     read_result(R.out, Result).

% create structure with pid and in/out pipes
open_session(R) :-
    % pipe(In, Out),
    process_create(path(bc),
    % bc -q
        ["-q"],
        [stdin(pipe(In)),
        stdout(pipe(Out)),
        process(Pid)]),
    dict_create(R, bcinstance, [pid:Pid,in:In,out:Out]).

close_instance(R) :-
    close(R.in),
    close(R.out),
    process_kill(R.pid).

with_command(Command, O) :-
    open_session(R),
    send_command(R, Command, O),
    close_instance(R).

如果我使用 with_command("2+3", O).,它似乎只是在等待输入,而不是输出“5”,不知道为什么。

首先,管道 会持续存在 直到其中一个进程关闭它。

您的示例 几乎 可以正常工作,除了一个小问题:

read/2 需要一个序言项,然后 一个点 。由于进程不发出 .read/2 等待进一步输入。

一个解决方案:例如使用 read_line_to_codes/2 而不是 read/2:

read_result(Out, Codes) :-
     read_line_to_codes(Out, Codes).

示例查询:

?- with_command("2+3", O).
O = [53].

验证:

?- X = 0'5.
X = 53.

如果有read_line_to_chars/2就好了,不是吗?