-- Source code for an article published at the Ada Home -- -- A Thick Ada 95 Binding for Unix Child Processes and Pipes -- by Jim Rogers -- February 1998 -- -- See -------------------------------------------------------------------------------- -- Implementation of a thick Ada binding to the UNIX popen and pclose -- commands -------------------------------------------------------------------------------- with Interfaces.C; use Interfaces.C; with Ada.Characters.Latin_1; package body Ada_Home.Unix.Pipe_Commands is LF : constant Interfaces.C_Streams.int := Character'Pos (Ada.Characters.Latin_1.LF); -- Unix end of line function popen (Command : char_array; Mode : char_array) return Files; pragma import (C, popen); function pclose (FileStream : FILEs) return Interfaces.C_Streams.int; pragma import (C, pclose); function execute (Command : in string; IO_type : in IO_Mode) return stream is Result : stream; begin case IO_Type is when read_file => Result.FileStream := popen(to_C(Command), to_C("r")); when write_file => Result.FileStream := popen(to_C(Command), to_C("w")); end case; Result.Mode := IO_Type; return Result; end execute; function read_next (FromFile : in stream) return unbounded_string is Result : Unbounded_String := Null_Unbounded_String; char_buf : Interfaces.C_Streams.int; temp : character; begin if Fromfile.Mode = write_file then raise Access_Error; end if; loop char_buf := fgetc (FromFile.FileStream); if char_buf = EOF then raise End_Of_File; end if; exit when char_buf = LF; -- end of line? temp := character'val (char_buf); Result := Result & temp; end loop; return Result; end read_next; procedure write_next (ToFile : in stream; Message : in string) is rc : Interfaces.C_Streams.int; begin if ToFile.Mode = read_file then raise Access_Error; end if; for I in Message'Range loop rc := fputc (character'pos(Message(I)), ToFile.FileStream); end loop; rc := fputc (LF, ToFile.FileStream); -- add end of line end write_next; procedure close (OpenFile : in stream) is rc : Interfaces.C_Streams.int; begin rc := pclose (OpenFile.FileStream); end close; end Ada_Home.Unix.Pipe_Commands;