LxF. Pipes - JulTob/Ada GitHub Wiki

16.11 Stdio Pipes

Pipes are the equivalent of shell command pipes formed by the '|' character. You can open a pipe to or from a shell command, depending if the pipe is for writing or reading respectively.

These single direction pipe commands are a part of the standard C library. function popen( command, mode : string ) return AStdioFileID; pragma import( C, popen, "popen" ); Opens a pipe to a Linux shell command.Mode can be "w" for write or "r" for read.

procedure pclose( result : out integer; fid : AStdioFileID); pragma import( C, pclose, "pclose" ); pragma import_valued_procedure( pclose ); Closes a pipe.

The following program prints to a printer by opening a pipe to the lpr command.

with Ada.Text_IO, System, SeqIO; use Ada.Text_IO;

procedure printer2 is -- a program for simple printing

---> Pipe Stuff -------------------------------------

type AStdioFileID is new System.Address; -- a pointer to a C standard IO (stdio) file id

function popen( command, mode : string ) return AStdioFileID; pragma import( C, popen, "popen" ); -- opens a pipe to command

procedure pclose( result : out integer; fid : AStdioFileID ); pragma import( C, pclose, "pclose" ); pragma import_valued_procedure( pclose); -- closes a pipe

function fputc( c : integer; fid : AStdioFileID ) return integer; pragma import( C, fputc, "fputc" ); -- part of standard C library.Writes one charctera to a file.

function fputs( s : string; fid : AStdioFileID ) return integer; pragma import( C, fputs, "fputs" ); -- part of standard C library.Writes a string to a file.

PipeID : AStdioFileID; -- File ID for lpr pipe

procedure BeginPrinting is -- open a pipe to lpr begin Put_Line( "Opening pipe to lpr ..." ); PipeID := popen( "lpr" & ASCII.NUL, "w"& ASCII.NUL); end BeginPrinting;

procedure EndPrinting is -- close the pipe.Result doesn't matter. -- Linux normally will not eject a page when -- printing is done, so we'll use a form feed. Result : integer; begin Result := fputc( character'pos( ASCII.FF ), PipeID); pclose( Result, PipeID ); end EndPrinting;

--> Input/Output Stuff --------------------------------

procedure Print( s : string ) is -- print a string to the pipe, with a carriage -- return and line feed. Result : integer; begin Result := fputs( s & ASCII.CR & ASCII.LF & ASCII.NUL, PipeID ); end Print;

begin

-- Open the pipe to the lpr command

Put_Line( "Starting to print..." ); BeginPrinting; Print( "Sales Report" ); Print( "------------" ); Print( "" );

Print( "Sales were good" );

-- Now, close the pipe.

EndPrinting;

Put_Line( "Program done...check the printer" );

end printer2;