본문 바로가기
Server | Network

[Tip] UNIX에서 밀리초(Miliseconds) 차이 구하는 방법

by 두루물 2012. 10. 26.

윈도우에는 컴퓨터 부팅이후의 시간단위를 알수있는 GetTickCount() 라는 편리한 함수가 있죠.

BSD계열의 UNIX에서는 조금더 계산해 주어야 합니다.

아래코드를 참조하세요..


/*KRKIM.NET Sample for Miliseconds Timeout : a part of DURUEDIT source code*/

int ClientSocket::PeekNetworkEvent(int timeout_milisec,bool bWrite)
{
	fd_set fd,*rfd = NULL,*wfd = NULL;
	struct timeval timeout,prevtime,curtime;
	int rv = 0;
	int retry = 0;
	int loop = 1,timeover = 0;
	char msg[80];
	//time_t dwtick = time(NULL);
	int milisec1,milisec2;
	if(!IsValid())
		return 0;

#ifdef WIN32
	DWORD dwTick = GetTickCount();
#else
	gettimeofday(&curtime, NULL);
	milisec1 = curtime.tv_sec * 1000 + curtime.tv_usec / 1000000;
#endif

	if(!bWrite)
		rfd = &fd;
	else
		wfd = &fd;
	FD_ZERO(&fd);
	
	do
	{
		rv = 0;
		FD_SET(m_hSocket,&fd);
		//timeout.tv_sec = nsec;
		//timeout.tv_usec = 0;
		timeout.tv_sec = timeout_milisec/1000;
		timeout.tv_usec = (timeout_milisec % 1000) * 1000;

		retry++;
		rv = select(m_hSocket+1, rfd, wfd, NULL, &timeout);
		wsprintf(msg,"wait select %d\n",rv);
		OutputDebugString(msg);
		if (rv == -1)
		{
			rv = 0;
			break;
		}
		else if (rv > 0)
		{
			rv = 1;
			break;
		}

		//if(time(NULL) > dwtick + timeout)
		//	timeover = 1;
#ifdef WIN32
		if(GetTickCount() >= dwTick + timeout_milisec)
			timeover = 1;
#else
		gettimeofday(&curtime, NULL);
		milisec2 = curtime.tv_sec * 1000 + curtime.tv_usec / 1000000;
		if(milisec2 >= milisec1 + timeout_milisec || (milisec1 >= milisec2 + timeout_milisec))
			timeover = 1;
#endif
		//컨트롤커넥션이 너무 오래 잡아먹으면 전반적인 행이 걸린다.
		//else if(conn->direction == PFDIRECTION_CONTROL && retry >=10){
		//	timeout = 1;
		//}
	}
	while (loop && !timeover);
	wsprintf(msg,"wait end %d ,timeover=%d\n",rv,timeover);
	OutputDebugString(msg);
	return rv;
}

'두루에디트' v2.1.0 #787 릴리즈(2012/09/10) 2012/09/12

'Server | Network' 카테고리의 다른 글

64bit Toad Setting  (0) 2012.10.29
SVN의 차세대 분산형 버전관리 시스템 Git Guide  (0) 2012.10.29
nginx 분석완료  (0) 2012.09.26
소켓 종료와 TIME_WAIT(Socket termination and TIME_WAIT)  (0) 2012.07.19
DB2 관련  (0) 2012.05.23