You are on page 1of 2

/************************************************************************/

/* PROGRAM NAME: Pipe_newA.c Pipe_newB.c */


/* */
/* using fdopen() */
/* */
/* DESCRIPTION: */
/* Using fork(), create one child process named CHILD. */
/* Using pipe(), establish a pipe between parent and child. */
/* Using dup2(), redirect stdin and stdout to the pipe. Or */
/* use fdopen() to associate a write stream to the write end of pipe */
/* you may also use fdopen() to associate a read stream to the read end */
/* Parent takes data from the keyboard(stdin) and adds a suffix */
/* "-PARENT-PROCESSED" to the data. Then parent passes the stamped */
/* data to child through pipe. Child marks "-CHILD-PROCESSED" at */
/* the end of string and prints the processed data on CRT(stdout). */
/* Above processes will be terminated with EOF input (Ctrl-D). */
/* */
/* To run this program, first compile both Pipe_exampleA.c */
/* and Pipe_exampleB.c in the same directory. */
/* */
/* cc -o Pipe_newB Pipe_newB.c */
/* cc -o Pipe_newA Pipe_newA.c */
/* */
/* Then execute "Pipe_newA". */
/************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
char token[100];
FILE *fout;
int p[2];
int pid;
pipe( p ); /* pipe between parent and child */
if((pid = fork()) == 0)
{/* child process P1 executes */
close(p[1]); /* close the fd of write end of the pipe */
if(dup2(p[0], 0 ) == -1 ) /* refer stdin to the read end of the pipe */
{
perror( "dup2 failed" );
_exit(1);
}
close(p[0]); /* close the fd of read end of the pipe */
execl("Pipe_newB","Pipe_newB","CHILD", 0);
/* execute 'Pipe_newB' */
perror("execl Pipe_newB failed");
_exit(1);
}
else if(pid < 0)
{/* fork() failed */
perror("fork CHILD failed");
exit(1);
}
/* parent executes */
close(p[0]); /* close the fd of the read end of pipe */
/* use fdopen() to associate a write stream to the write end
of the pipe between parent and child */
if( ( fout = fdopen( p[1], "w" ) ) == 0 )
{
perror( "fdopen failed" );
exit(1);
}
printf( "Please input a string:\n" );
while( scanf( "%s", token ) != EOF )
{
if( fprintf( fout, "%s-Parent\n", token ) == EOF )
{
perror( "fprintf failed" );
exit(1);
}
fflush( fout );
}
close(1); /* close reference to pipe in order to sending 'EOF' */
wait(NULL);
return(0);
}

You might also like