Created
June 14, 2010 19:28
-
-
Save meekrosoft/438160 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <signal.h> | |
#include <unistd.h> | |
#include <iostream> | |
#include <stdint.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <netinet/tcp.h> | |
#include <gtest/gtest.h> | |
typedef void Sigfunc(int); | |
Sigfunc * signal_intr(int signo, Sigfunc * func) | |
{ | |
struct sigaction act, oact; | |
act.sa_handler = func; | |
sigemptyset(&act.sa_mask); | |
act.sa_flags = SA_INTERRUPT; | |
if(sigaction(signo, &act, &oact) < 0) | |
return SIG_ERR; | |
return oact.sa_handler; | |
} | |
#define ALARM_RESTART_TIMEOUT_SECONDS (5) | |
void acceptAlarm(int signalVal) | |
{ | |
signal_intr(SIGALRM, SIG_IGN); | |
signal_intr(SIGALRM, acceptAlarm); | |
alarm(ALARM_RESTART_TIMEOUT_SECONDS); | |
FAIL() << "Alarm: Timeout on test, signal "<< signalVal; | |
} | |
class TimeoutTest : public testing::Test | |
{ | |
public: | |
uint32_t timeoutSecs; | |
void SetUp() | |
{ | |
timeoutSecs = 5; | |
// Set up a timeout for every test | |
signal_intr(SIGALRM, acceptAlarm); | |
alarm(timeoutSecs); | |
}; | |
void TearDown() | |
{ | |
alarm(0); // cancel alarm | |
}; | |
}; | |
TEST_F(TimeoutTest, doesntTimeOutIfLessThanPeriod) | |
{ | |
std::cout << "Hello world" << std::endl; | |
} | |
TEST_F(TimeoutTest, timeOutIfMoreThanPeriod) | |
{ | |
sleep(10); | |
} | |
TEST_F(TimeoutTest, timeOutMultipleBlockingIo) | |
{ | |
int sock = socket(PF_INET, SOCK_STREAM, 0); | |
ASSERT_TRUE(sock > 0); | |
struct sockaddr_in server_addr; | |
server_addr.sin_family = AF_INET; | |
server_addr.sin_addr.s_addr = INADDR_ANY; | |
server_addr.sin_port = htons(11111); | |
bind(sock, (sockaddr *) &server_addr, sizeof(server_addr)); | |
ASSERT_EQ(0, listen(sock, 10)); | |
socklen_t addrlen = (socklen_t) sizeof(server_addr); | |
// First blocking call | |
accept(sock, (sockaddr *) &server_addr, &addrlen); | |
std::cout << "Continuing the test.." << std::endl; | |
// After timeout will continue here.. | |
uint32_t numBytes = 100; | |
uint8_t buffer[100]; | |
recv(sock, buffer, numBytes, 0); // this should also block | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for share this code. !!!