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

时间:2018-03-29 10:55:04

标签: prolog swi-prolog

我试图通过bcpipes实例交谈,但是我的代码每次都会运行新实例。是否可以保持连接持久直到我关闭它?

:- 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”,不知道为什么。

1 个答案:

答案 0 :(得分:2)

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

您的示例几乎按预期工作,除了一个小问题:

read/2需要一个Prolog术语,然后一个点。由于该过程未发出.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 会很棒,不是吗?