我有一个signal
,在其中设置了回调处理程序,然后在函数中调用alarm(1)
,这样我的程序将在1秒钟后超时。超时后,我希望它重试相同的阻塞调用recvfrom()
,直到设置为MAX_ATTEMPTS
的5。
问题:
它仅重试2次,然后退出程序。知道可能出什么问题了吗?
/* declate signal for setting alarm */
signal(SIGALRM, timeout_hdler);
int attempts = 0;
while(1) {
if(attempts > MAX_ATTEMPTS) {
printf("Connection is not working, EXITING program");
s.curr_state = CLOSED;
/* we assume connection is failing so we shut down */
exit(-1);
}
if (s.curr_state == CLOSED) {
printf("Sending SYN_packet with seqnum: %d...\n", SYN_packet->seqnum);
if (sendto(sockfd, SYN_packet, sizeof(SYN_packet), 0, server, socklen) == -1) {
perror("Sendto error");
exit(-1);
}
s.curr_state = SYN_SENT;
printf("Current state SYN_SENT: %d\n", s.curr_state);
}
if (s.curr_state == SYN_SENT) {
alarm(1);
attempts++;
printf("\nAttempt number: %d\n", attempts);
printf("Waiting for SYNACK_packet...\n");
if (recvfrom(
sockfd, SYNACK_packet, sizeof(*SYNACK_packet), 0, (struct sockaddr *) &server, &socklen) == -1)
{
if (errno != EINTR) {
perror("Recvfrom SYNACK_packet error\n");
s.curr_state = CLOSED;
exit(-1);
}
}
if ((SYNACK_packet->type == SYNACK) && (validate_packet(SYNACK_packet) == 1)) {
printf("SYNACK_packet received\n");
s.address = *(struct sockaddr *) &server;
s.sock_len = socklen;
s.curr_state = ESTABLISHED;
s.seq_num = SYNACK_packet->seqnum;
printf("Current state ESTABLISHED: %d\n", s.curr_state);
return sockfd;
}
}
}
处理程序(除了打印外什么也不做):
void timeout_hdler(int signum) {
printf("TIMEOUT has occured with signum: %d", signum);
}
这是我的控制台中的输出(来自printf
语句):
In Connect() with socket: 4, server: 2, socklen: 16
Sending SYN_packet with seqnum: 67...
Current state SYN_SENT: 1
Attempt number: 1
Waiting for SYNACK_packet...
TIMEOUT has occured with signum: 14
Attempt number: 2
Waiting for SYNACK_packet...
Alarm clock
为什么仅2次尝试就退出程序?理想情况下,我希望它在关闭连接之前重试5次(这是使用UDP的Go Back N实现)
更新
我通过在处理程序中重新安装signal
:signal(SIGALRM, timeout_hdler);
解决了该问题。但是为什么呢?我做错了吗?
void timeout_hdler(int signum) {
printf("TIMEOUT has occured with signum: %d", signum);
signal(SIGALRM, timeout_hdler);
}
答案 0 :(得分:1)
signal
的语义取决于操作系统和libc。但是根据您的特定情况下的输出,在首次调用处理程序函数后,信号处理程序处理程序将重置为默认值。如果再次触发信号(即Alarm clock
),则默认值将导致程序退出,并在输出中看到退出。
来自the documentation of signal in Linux:
signal()的唯一可移植用法是将信号的处置设置为 SIG_DFL或SIG_IGN。 ....
在原始UNIX系统中,当建立处理程序时 使用signal()通过传递信号来调用,信号的处置将重置为SIG_DFL ,而系统没有 阻止其他信号实例的传递。 ...
换句话说:不要使用signal
。相反,您应该使用sigaction
:
POSIX.1通过指定sigaction(2)解决了可移植性问题, 当信号处理程序处于以下状态时,提供对语义的显式控制 援引;使用该接口而不是signal()。