str_cli_poll03.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "unp.h"
  2. #include <sys/devpoll.h>
  3. void
  4. str_cli(FILE *fp, int sockfd)
  5. {
  6. int stdineof;
  7. char buf[MAXLINE];
  8. int n;
  9. int wfd;
  10. struct pollfd pollfd[2];
  11. struct dvpoll dopoll;
  12. int i;
  13. int result;
  14. wfd = Open("/dev/poll", O_RDWR, 0);
  15. pollfd[0].fd = fileno(fp);
  16. pollfd[0].events = POLLIN;
  17. pollfd[0].revents = 0;
  18. pollfd[1].fd = sockfd;
  19. pollfd[1].events = POLLIN;
  20. pollfd[1].revents = 0;
  21. Write(wfd, pollfd, sizeof(struct pollfd) * 2);
  22. stdineof = 0;
  23. for ( ; ; ) {
  24. /* block until /dev/poll says something is ready */
  25. dopoll.dp_timeout = -1;
  26. dopoll.dp_nfds = 2;
  27. dopoll.dp_fds = pollfd;
  28. result = Ioctl(wfd, DP_POLL, &dopoll);
  29. /* loop through ready file descriptors */
  30. for (i = 0; i < result; i++) {
  31. if (dopoll.dp_fds[i].fd == sockfd) {
  32. /* socket is readable */
  33. if ( (n = Read(sockfd, buf, MAXLINE)) == 0) {
  34. if (stdineof == 1)
  35. return; /* normal termination */
  36. else
  37. err_quit("str_cli: server terminated prematurely");
  38. }
  39. Write(fileno(stdout), buf, n);
  40. } else {
  41. /* input is readable */
  42. if ( (n = Read(fileno(fp), buf, MAXLINE)) == 0) {
  43. stdineof = 1;
  44. Shutdown(sockfd, SHUT_WR); /* send FIN */
  45. continue;
  46. }
  47. Writen(sockfd, buf, n);
  48. }
  49. }
  50. }
  51. }