Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
write to pipe then read the pipe back into the program
02-03-2010, 01:24 PM
Post: #1
write to pipe then read the pipe back into the program
Example of piping with unix api using free pascal compiler
Code:
program pipeExample(input,output);
{This example was coded by jerome scott II aka codecaine}
uses
    BaseUnix, unixtype, Unix;
const
BUFF_MAX = 500;
var
    fpIn, fpOut : TFilDes;
    child : TPid;
    x : Integer;
    buff : Array of char;
    names : Array [1..5] of ANSIString = ('bill','jerome','adam','lewis','mark');
begin
    
    //set the length of buff
    setLength(buff,BUFF_MAX);
    
    //create 2 pipes
    FpPipe(fpIn);
    FpPipe(fpOut);
    
    //create new process
    child := fpFork();
    
    //check if new process failed
    if child = -1 then
    begin
        writeLn('fork failed');
        exit;
    end;
    
    //parent child
    if child <> 0 then
    begin
        FpClose(fpIn[0]); //no need to read from pipe
        FpClose(fpOut[1]); //no need to write to pipe
        
        //loop and write to the pipe
        for x := 1 To 5 do
        begin
            names[x] := names[x] + #10;
            FpWrite( fpIn[1], PChar(names[x]), Length(names[x]));
        end;
        FpClose(fpIn[1]); //close the pipe so let read know it is ok to go
        
        //read the pipe data back in to the program here you can maniulate the data if you like
        FpRead(fpout[0],buff[0],BUFF_MAX);
        writeln('Result:');
        for x := 0 to length(buff) do
            write(buff[x]);
            
        
    end
    else
    begin
        FpClose(fpIn[1]); //no need to write to pipe
        FpClose(fpOut[0]); //no need to read from pipe
        FpDup2(fpIn[0],0);
        FpDup2(fpOut[1],1);
        FpExecLP('sort', []);
    end;
    
    
end.


Attached File(s)
.zip  pipeExample.py.zip (Size: 876 bytes / Downloads: 0)
Visit this user's website Find all posts by this user
Quote this message in a reply
02-03-2010, 11:50 PM
Post: #2
RE: write to pipe then read the pipe back into the program
Great code, same as in C++ setLength() is very good function, i use it for arrays !

"I dont know with what weapons World War 3 will be fought with, but i know World War 4 will be fought with stones and sticks" - Albert Einstein
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: