
pipes are more simple form of IPC. Written in Unix for the first time .Now, let us clear some useful points.
you know about "FILE *" from stdio.h, right? You know how you have all those nice functions like fopen(), fclose(), fwrite(), and so on? Well, those are actually high level functions that are implemented using file descriptors, which use system calls such as open(), creat(), close(), and write(). File descriptors are simply ints that are analogous to FILE *'s in stdio.h.
Open --> Prepare for input or output operations.
Close --> Stop previous operations and return resources.
Read --> Get data and place in application memory.
Write --> Put data from application memory and send control.
Control (ioctl) --> Set options such as buffer sizes and connection behavior.
ok? here some more useful data.....For example, stdin(standard input) is file descriptor "0", stdout(std output) is "1", and stderr(std error) is "2".
Basically, pipe() takes an array of two ints as an argument. Assuming no errors, it connects two file descriptors and returns them in the array. The first element of the array is the reading-end of the pipe, the second is the writing end.
Now,let us work ..
First, we'll have the parent make a pipe. Secondly, we'll fork(). Now, the fork() man page tells us that the child will receive a copy of all the parent's file descriptors, and this includes a copy of the pipe's file descriptors. Alors, the child will be able to send stuff to the write-end of the pipe, and the parent will get it off the read-end. Like this:
the reason i omit <> is tht it is the syntax of html..
#include sys/types.h
#include unistd.h
#include stdio.h
#include stdlib.h
int main()
{
int pfds[2];
pid_t childpid;
char buf[30];
if(pipe(pfds)>= 0)/* pipe() executed and if success*/
{
/* now fork()*/
childpid=fork();
if( childpid >= 0 )
{
if(childpid ==0)
{
/*child process*/
printf("Hi..I'm child process..");
printf("Writing 'HELLO' to the pipe ... ");
/*child write some data */
write(pfds[1],"HELLO",7);
printf("\nChild : Exiting..Bye...");
exit(0);
}
else
{
printf("\n\nHi..I'm parent...Reading from the pipe");
/*parent read data from child*/
read(pfds[0],buf,7);
printf("\nParent: the child say %s",buf);
printf("\nParent: Exiting..Bye\n");
exit(0);
}
}
else
{
perror("Fork");/*error in executing fork()*/
exit(0);
}
}
else
{
perror("pipe");/*error in executing pipe() */
exit(0);
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.