File: pipe.pl

package info (click to toggle)
swi-prolog 9.0.4%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 82,408 kB
  • sloc: ansic: 387,503; perl: 359,326; cpp: 6,613; lisp: 6,247; java: 5,540; sh: 3,147; javascript: 2,668; python: 1,900; ruby: 1,594; yacc: 845; makefile: 428; xml: 317; sed: 12; sql: 6
file content (54 lines) | stat: -rw-r--r-- 1,212 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*  Part of SWI-Prolog

    Author:  Jan Wielemaker
    This example code is in the public domain
*/

:- module(subcommand,
          [ pipe_through_command/3      % +Command, +In, -Out
          ]).
:- use_module(library(unix)).

%       pipe_through_command(+Command, +In, -Out)
%
%       Pipe text In through command Command and put the output of command
%       in Out.
%
%       Example:
%
%               ?- pipe_through_command(tr('a-z', 'A-Z'), hello, X)
%
%               X = 'HELLO'

pipe_through_command(Command, In, Out) :-
    pipe(ChildIn, MeOut),
    pipe(MeIn,  ChildOut),
    fork(Pid),
    (   Pid == child,
        close(MeOut),
        close(MeIn),
        dup(ChildIn, 0),
        dup(ChildOut, 1),
        close(ChildIn),
        close(ChildOut),
        exec(Command)
    ;   close(ChildIn),
        close(ChildOut),
        write(MeOut, In),
        close(MeOut),
        read_input(MeIn, Out),
        close(MeIn),
        wait(Pid, _Status)          % avoid zombi
    ).


read_input(In, Atom) :-
    get_code(In, C0),
    read_input(C0, In, Codes),
    atom_codes(Atom, Codes).

read_input(-1, _, []) :- !.
read_input(C, In, [C|T]) :-
    get_code(In, C1),
    read_input(C1, In, T).