Anonymous pipe and Named pipe
Introduction:
Anonymous pipe and Named pipe are usually used for communication between two different tasks.
Anonymous pipe:
It does not have name, and can be applied in the shell by using ' | '. It is unidirectional.
For example, p1 | p2
Here anonymous pipe usually is used in case of standard output and standard input which are related to the shell. So here you can use anonymous pipe ' | ' directly to transfer data from p1 to p2. So here must remember that the output and input are both for shell which means usually using functions printf() for output and scanf() for input or something like this.
Named pipe:
However, named pipe is related to a dev file which is more flexible. So in this case, you can transfer the data like writing/reading to/from file which is already familiar to you. We can create a pipe by using mkfifo /dev/mypipe where mkfifo is a new command, and in some old version of Linux you may use mknod p /dev/mypipe. But we recommend you use mkfifo /dev/mypipe.
Then we can write our applications like the following to test mypipe:
Read file:
//fifo_read.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void)
{
FILE *fp;
char buf[20];
/* Create the FIFO if it does not exist*/
umask(0);
mknod("mypipe", S_IFIO|0666, 0);
while(1)
{
fp=fopen("mypipe", "r");
fgets(buf, 20, fp);
printf("We received: %s\n", buf);
fclose(fp);
}
return(0);
}
Write file:
//fifo_write.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp;
if((fp=fopen("pipe", "w"))==NULL)
{
fprintf(stderr, "fopen caused an error\n");
exit(1);
}
fputs(argv[1], fp);
fclose(fp);
return(0);
}
Blocking and nonblocking:
Here we use fopen("mypipe", "r") open mypipe as a normal file which is default for blocking. So the after writing, the program is blocked and wait for another program to read data. Similarly, after execute the read program, it will be blocked and wait until there is an another program to write in this buffer.
If it is nonblocking, then neither program will be waiting, they will just be executed until the end. But here we cannot use stream functions anymore, because they do not have the option for nonblocking, so you have to use file descriptors which is operated using system call (like operating drivers). So in file descriptor we can open the buffer as nonblocking as following:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int ifd;
...
ifd=open("/dev/mypipe", O_RDONLY | O_NONBLOCK);
...
read(ifd, buf, 20);
The differences between streams and file descriptors:
Warning:
Unless you really really have to use nonblocking buffer, please use stream to do blocking buffer.
Comments
Post a Comment