Total Pageviews

Sunday 11 January 2015


/*Using PIPE to write a file from child process to a Parent process in linux*/

 

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<string.h>
#include<string>
#include<iostream>
using namespace std;
int main(void)
{
       int     fd[2], nbytes;
        pid_t   childpid;
      //char    string[] = "Hello, world!\n";
        char    readbuffer[180];
        char   writebuffer[180];

        pipe(fd);

        if((childpid = fork()) == -1)
        {
                perror("fork");

        }

        if(childpid == 0)
        {
                /* Child process closes up input side of pipe */
                close(fd[0]);

                /* Send "string" through the output side of pipe */
                FILE *fin=fopen("cs345.txt","r");
                if(fin==NULL)cout<<"error";
                cout<<"in child \n";
               // getline(fin,s1,'\n');
            while( fgets(writebuffer,180,fin)!=NULL)
                {cout<<s;
                write(fd[1],writebuffer,180);

               }
                close(fd[1]);
               return 0;
               }
        else
        {
                /* Parent process closes up output side of pipe */
               sleep(1);
                close(fd[1]);
                cout <<"In parent \n";
                FILE* fout=fopen("cs345-lab.txt","w");
                /* Read in a string from the pipe */
                while((nbytes = read(fd[0], readbuffer, sizeof(readbuffer)))!=0)

                {printf("Received string: %s", readbuffer);
                fputs(readbuffer,fout);
          }      return 0;
        }

        return(0);
}

No comments:

Post a Comment