Professional Documents
Culture Documents
Pipeexample
Pipeexample
#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);
}