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).
|