发送端三个新函数
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
static int sockfd;
static int nsec;
static int maxnprobes;
static int nprobes;
void sig_urg(int signo)
{
int n;
char c;
if ((n = recv(sockfd, &c, 1, MSG_OOB)) < 0)
{
if (errno != EWOULDBLOCK)
{
perror("recv");
exit(-1);
}
}
nprobes = 0;
return;
}
void sig_alrm(int signo)
{
if (++nprobes > maxnprobes)
{
fprintf(stderr, "server is unreachable.\n");
exit(0);
}
send(sockfd, "1", 1, MSG_OOB);
alarm(nsec);
return;
}
void heartbeat_cli(int fd, int nsec_arg, int maxnprobes_arg)
{
sockfd = fd;
nsec = nsec_arg;
if (nsec < 1)
{
nsec = 1;
}
maxnprobes = maxnprobes_arg;
if (maxnprobes < nsec)
{
maxnprobes = nsec;
}
nprobes = 0;
signal(SIGURG, sig_urg);
fcntl(sockfd, F_SETOWN, getpid());
signal(SIGALRM, sig_alrm);
alarm(nsec);
}
接收端三个新函数
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
static int sockfd;
static int nsec;
static int maxnprobes;
static int nprobes;
void sig_urg(int signo)
{
int n;
char c;
if ((n = recv(sockfd, &c, 1, MSG_OOB)) < 0)
{
if (errno != EWOULDBLOCK)
{
perror("recv");
exit(-1);
}
}
send(sockfd, &c, 1, MSG_OOB);
nprobes = 0;
return;
}
void sig_alrm(int signo)
{
if (++nprobes > maxnprobes)
{
fprintf(stderr, "server is unreachable.\n");
exit(0);
}
alarm(nsec);
return;
}
void heartbeat_serv(int fd, int nsec_arg, int maxnprobes_arg)
{
sockfd = fd;
nsec = nsec_arg;
if (nsec < 1)
{
nsec = 1;
}
maxnprobes = maxnprobes_arg;
if (maxnprobes < nsec)
{
maxnprobes = nsec;
}
nprobes = 0;
signal(SIGURG, sig_urg);
fcntl(sockfd, F_SETOWN, getpid());
signal(SIGALRM, sig_alrm);
alarm(nsec);
}