File: pipe.pl

package info (click to toggle)
swi-prolog-packages 5.0.1-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 50,688 kB
  • ctags: 25,904
  • sloc: ansic: 195,096; perl: 91,425; cpp: 7,660; sh: 3,046; makefile: 2,750; yacc: 843; awk: 14; sed: 12
file content (60 lines) | stat: -rw-r--r-- 1,309 bytes parent folder | download | duplicates (2)
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
55
56
57
58
59
60
/*  $Id: pipe.pl,v 1.1 2000/10/09 10:18:32 jan Exp $

    Part of SWI-Prolog

    Author:  Jan Wielemaker
    E-mail:  jan@swi.psy.uva.nl
    WWW:     http://www.swi.psy.uva.nl/projects/SWI-Prolog/
    Copying: GPL-2.  See the file COPYING or http://www.gnu.org

    Copyright (C) 1990-2000 SWI, University of Amsterdam. All rights reserved.
*/

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