/**
* @file heartbeatcli.c
* 紧急数据实现心跳包
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
static int sockfd; // 套接字
static int nsec; // 每次定时的秒数,>=1
static int maxnprobes; // 最大的等待回应的次数
static int nprobes; // 当前回应的次数,如果等待max没有回应,断开连接
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
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
static int sockfd; // 套接字
static int nsec; // 每次定时的秒数,>=1
static int maxnprobes; // 最大的等待回应的次数
static int nprobes; // 当前回应的次数,如果等待max没有回应,断开连接
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);
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)