how do we use named pipes for communicating between processes in unix system?? it will be helpful if u could give any simple example program .....i m trying to write it using a c program ...
Inter process communication using named pipes in unix .....?
I have experience with such stuff (such as writing my own basic shell with I/O redirection and backgrounding). But, I found this which saves me the time of typing a lot:
http://developers.sun.com/solaris/articl...
It has great explanations AND examples. If you have questions after that, we're here. :-)
############
Update:
Three things:
[[ 1 ]]
I included %26lt;stdlib.h%26gt;. This is because my system didn't recognize exit() without it.
[[ 2 ]]
You need to open the named pipe with proper permissions. (*Note 1) If you look at the permissions of 'mypipe' how you had it, it has p---------, or chmod 000. That's no good if you can't read or write. :-p Thus, when you open it, OR 0644 in the mode:
mkfifo("mypipe",S_IFIFO|0644), instead of
mkfifo("mypipe",S_IFIFO)
[[ 3 ]]
You need to open both ends of the pipe first. open() is blocking, meaning it waits for the other end of the pipe to be open. (*Note 2) To solve this, you can open one as non-blocking by ORing O_NDELAY. However, if you open, write, and close one end before the other end is opened, it will have sent everything before the other end was ready to look for it. The reading end needs to be open to receive what's written.
Thus, you need to open the reading end (non-blockingly, if that's a word) before you write on the other end. Below is your code with these aforementioned slight modifications, now working:
{{{{{{ BEGIN CODE }}}}}}}}
#include %26lt;fcntl.h%26gt;
#include %26lt;stdio.h%26gt;
#include %26lt;stdlib.h%26gt;
#include %26lt;string.h%26gt;
#include %26lt;sys/stat.h%26gt;
#include %26lt;sys/types.h%26gt;
int main ()
{
int fd1,fd2;
char buf[100];
char *phrase = "Stuff this in your pipe and smoke it";
if (mkfifo("mypipe",S_IFIFO|0644))
{
perror("mknod66");
exit(1);
}
fd2 = open ( "mypipe", O_RDONLY|O_NDELAY);
fd1 = open ( "mypipe", O_WRONLY);
write (fd1, phrase, strlen (phrase)+1 );
close (fd1);
read ( fd2, buf, 100 );
printf ( "%s \n", buf );
close (fd2);
}
{{{{{{{ END CODE }}}}}}}}
*Note 1:
If you do some error checking on open(), you'll see that without proper permissions, open() returns -1 with an error: "Permission denied."
*Note 2:
You can witness the blocking in action. From my code above, remove the "|O_NDELAY" and your program will just wait... and wait.... and wait... (until you kill it or you open up the other end of the pipe somewhere else). In your code, you opened both ends of the pipe with O_RDWR, both reading and writing. The blocking is not an issue if you open it like that, because both a reader and a writer exist on the pipe, so it's happy and doesn't block.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment