Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
pipes to write and read
02-02-2010, 04:27 PM
Post: #1
pipes to write and read
This program writes to the sort program then pipe the data back into the program to read it instead of the standard output.

Code:
#include <string>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/uio.h>
#include <unistd.h>

#define MAXSTRS 5

using namespace std;

int main(void)
{
        int     child_in[2], child_out[2], nbytes;
        pid_t   childpid;
        string strings[MAXSTRS] = { "echo\n", "bravo\n", "alpha\n",
                                  "charlie\n", "delta\n"};
        char buffer[255];


        pipe(child_in);
    pipe(child_out);
    
    childpid = fork();

        if(childpid != 0)
        {
        close(child_in[0]); // read end of the pipe isnt used in this process
        close(child_out[1]); //write end isnt used here
        
        for(int i = 0; i < MAXSTRS; i++)
        {
            write(child_in[1], strings[i].c_str(), strings[i].size());
        }

        close(child_in[1]); //so sort gets to EOF
        //sort will finish reading here then sort and send the results to the child_out pipe
        
        int line = 0;
        FILE *test = fdopen(child_out[0],"r");
        while(fgets(buffer,sizeof(buffer),test) != 0)
        {
            //replace this code that loads the stuff into an array
            line++;
            cout<<line<<". "<<buffer;
        }
    
        wait(NULL);
        }
        else
        {
        close(child_in[1]); // write end of the pipe isnt used in this process
        close(child_out[0]); //read end isnt used here
        dup2(child_in[0], 0);
        dup2(child_out[1], 1);
                execlp("sort", "sort", NULL);
        }
        
        return(0);
}
Visit this user's website Find all posts by this user
Quote this message in a reply
02-02-2010, 07:19 PM
Post: #2
RE: pipes to write and read
Great code. You used really good libs there !

There's a fine line between genius and insanity. I have erased this line.
Oscar Levant
There's a fine line between an administrator and black hat hacker. I have erased this line.
Dr DEBCOL
Visit this user's website Find all posts by this user
Quote this message in a reply
02-03-2010, 12:23 AM (This post was last modified: 02-03-2010 12:24 AM by codecaine.)
Post: #3
RE: pipes to write and read
You that is just a small look at unix api Smile It is very powerful windows have nothing like it to pipe data. free pascal compiler has full access to unix api also
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: