heartbeatcli.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include "unp.h"
  2. static int servfd;
  3. static int nsec; /* #seconds betweeen each alarm */
  4. static int maxnprobes; /* #probes w/no response before quit */
  5. static int nprobes; /* #probes since last server response */
  6. static void sig_urg(int), sig_alrm(int);
  7. void
  8. heartbeat_cli(int servfd_arg, int nsec_arg, int maxnprobes_arg)
  9. {
  10. servfd = servfd_arg; /* set globals for signal handlers */
  11. if ( (nsec = nsec_arg) < 1)
  12. nsec = 1;
  13. if ( (maxnprobes = maxnprobes_arg) < nsec)
  14. maxnprobes = nsec;
  15. nprobes = 0;
  16. Signal(SIGURG, sig_urg);
  17. Fcntl(servfd, F_SETOWN, getpid());
  18. Signal(SIGALRM, sig_alrm);
  19. alarm(nsec);
  20. }
  21. static void
  22. sig_urg(int signo)
  23. {
  24. int n;
  25. char c;
  26. if ( (n = recv(servfd, &c, 1, MSG_OOB)) < 0) {
  27. if (errno != EWOULDBLOCK)
  28. err_sys("recv error");
  29. }
  30. nprobes = 0; /* reset counter */
  31. return; /* may interrupt client code */
  32. }
  33. static void
  34. sig_alrm(int signo)
  35. {
  36. if (++nprobes > maxnprobes) {
  37. fprintf(stderr, "server is unreachable\n");
  38. exit(0);
  39. }
  40. Send(servfd, "1", 1, MSG_OOB);
  41. alarm(nsec);
  42. return; /* may interrupt client code */
  43. }