strcliselect02.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include "unp.h"
  2. void
  3. str_cli(FILE *fp, int sockfd)
  4. {
  5. int maxfdp1, stdineof = 0;
  6. fd_set rset;
  7. char sendline[MAXLINE], recvline[MAXLINE];
  8. heartbeat_cli(sockfd, 1, 5);
  9. FD_ZERO(&rset);
  10. for ( ; ; ) {
  11. if (stdineof == 0)
  12. FD_SET(fileno(fp), &rset);
  13. FD_SET(sockfd, &rset);
  14. maxfdp1 = max(fileno(fp), sockfd) + 1;
  15. if (select(maxfdp1, &rset, NULL, NULL, NULL) < 0) {
  16. if (errno == EINTR)
  17. continue;
  18. else
  19. err_sys("select error");
  20. }
  21. if (FD_ISSET(sockfd, &rset)) { /* socket is readable */
  22. if (Readline(sockfd, recvline, MAXLINE) == 0) {
  23. if (stdineof == 1)
  24. return; /* normal termination */
  25. else
  26. err_quit("str_cli: server terminated prematurely");
  27. }
  28. Writen(STDOUT_FILENO, recvline, strlen(recvline));
  29. }
  30. if (FD_ISSET(fileno(fp), &rset)) { /* input is readable */
  31. if (Fgets(sendline, MAXLINE, fp) == NULL) {
  32. stdineof = 1;
  33. alarm(0); /* turn off heartbeat */
  34. Shutdown(sockfd, SHUT_WR); /* send FIN */
  35. FD_CLR(fileno(fp), &rset);
  36. continue;
  37. }
  38. Writen(sockfd, sendline, strlen(sendline));
  39. }
  40. }
  41. }