Bidirectional FIFO
I would like to implement a bi-directional fifo. The code below works, but it doesn't use a bidirectional fifo. I've searched all over the internet but couldn't find a good example ...
How can i do this?
Thanks,
WRITER.c:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#define MAXLINE 4096
#define READ 0
#define WRITE 1
int main (int argc, char** argv)
{
int a, b, fd;
do {
fd=open("/tmp/myfifo",O_WRONLY);
if (fd==-1) sleep(1);
} while (fd==-1);
while (1) {
scanf("%d", &a);
scanf("%d", &b);
write(fd,&a,sizeof(int));
write(fd,&b,sizeof(int));
if (a == 0 && b == 0)
{
break;
}
}
close(fd);
return 0;
}
READER.c:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#define MAXLINE 4096
#define READ 0
#define WRITE 1
int main(void)
{
int n1, n2;
int fd;
mkfifo("/tmp/myfifo",0660);
fd=open("/tmp/myfifo",O_RDONLY);
while(read(fd, &n1, sizeof(int) ))
{
read(fd, &n2, sizeof(int));
if (n1 == 0 && n2 == 0)
{
break;
}
printf("soma: %d\n",n1+n2);
printf("diferenca: %d\n", n1-n2);
printf("divisao: %f\n", n1/(double)n2);
printf("multiplicacao: %d\n", n1*n2);
}
close(fd);
return 0;
}
a source to share
FIFOs (also known as named pipes) provide an interprocess communication bearer. FIFO has end of read and end of write. Data written to the end of the FIFO write can be read from the read end of the FIFO. Since they are unidirectional, a pair of FIFOs is required for bidirectional communication.
As cHao suggested , another option is to use a Unix socket. Unix domain sockets are slightly more expensive to set up (socket creation, initialization, and connection) than FIFOs, but are more flexible and offer bidirectional communication.
a source to share
Another option is to use psudo-terminal (ptty). You can also use TCP sockets, which have a higher overhead than UNIX sockets, but will work.
Bidirectional pipes are often discouraged due to the possibility of deadlock (prog1 is waiting for data from prog2, which is waiting for data from prog1, which is waiting for data from prog2 ...), but this can happen with any of the workarounds and can also occur with commonly used protocols. such as SMTP (Simple Mail Transport Protocol) as each party plays a role in the conversation.
If you think a deadlock might occur, you may want at least one party to have a timeout, which you can do with one of the polling functions (including polling, select, pselect, and epoll_ *) or by arranging SIGALM for delivery (with an alarm or several other features that allow for shorter time and more control) so your program can break the deadlock.
a source to share