先看poll():
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <poll.h> #define oops(x, n) { perror(x); exit(n); } int main()
{
mkfifo("fifo1", );
mkfifo("fifo2", ); int fd1 = open("fifo1", O_RDWR);
int fd2 = open("fifo2", O_RDWR);
char buf[];
for(;;)
{
struct pollfd pfd[] = {{, POLLIN}, {fd1, POLLIN}, {fd2, POLLIN}};
int ret = poll(pfd, , );
if(ret > )
{
if(pfd[].revents&POLLIN)
{
scanf(" %[^\n]", buf);
printf("keypad:%s\n", buf);
if(strcmp(buf, "quit") == ) break;
}
if(pfd[].revents&POLLIN)
{
int n = read(fd1, buf, sizeof(buf));
buf[n] = '\0';
printf("fifo1:%s", buf);
}
if(pfd[].revents&POLLIN)
{
int n = read(fd2, buf, sizeof(buf));
buf[n] = '\0';
printf("fifo2:%s", buf);
}
} }
close(fd1);
close(fd2);
unlink("fifo1");
unlink("fifo2"); return ;
}
再来说说select():
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <poll.h> #define oops(x, n) { perror(x); exit(n); } int main()
{
mkfifo("fifo1", );
mkfifo("fifo2", ); int fd1 = open("fifo1", O_RDWR);
int fd2 = open("fifo2", O_RDWR);
char buf[];
for(;;)
{
struct pollfd pfd[] = {{, POLLIN}, {fd1, POLLIN}, {fd2, POLLIN}};
int ret = poll(pfd, , );
if(ret > )
{
if(pfd[].revents&POLLIN)
{
scanf(" %[^\n]", buf);
printf("keypad:%s\n", buf);
if(strcmp(buf, "quit") == ) break;
}
if(pfd[].revents&POLLIN)
{
int n = read(fd1, buf, sizeof(buf));
buf[n] = '\0';
printf("fifo1:%s", buf);
}
if(pfd[].revents&POLLIN)
{
int n = read(fd2, buf, sizeof(buf));
buf[n] = '\0';
printf("fifo2:%s", buf);
}
} }
close(fd1);
close(fd2);
unlink("fifo1");
unlink("fifo2"); return ;
}