c언어에서 많이 사용하는 것이 바로 소켓 통신일겁니다.
저는 네트워크쪽 개발자이다 보니, 소켓 통신을 주로 사용합니다.
c언어 소켓 함수는 block되는 함수들이 많습니다.
그러나 자체적으로 타임아웃을 제공해주지 않기 때문에, 저 같은 경우는 select 함수를 이용하여 타임아웃을 캐치합니다.
예제 소스는 아래와 같습니다. 아래의 소스는 select에 타임아웃 1초를 걸고, 소켓 fd에 반응이 없으면, block되는 함수를 빠져나오는 것입니다.
======================================================================================================
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <errno.h>
#include <fcntl.h>
.... 생략 .....
/* select variable */
struct timeval timeout = {};
fd_set reads = {};
/* Select Setting */
FD_ZERO(&reads);
FD_SET(sock, &reads);
/* timeout setting */
timeout.tv_sec = 1; /* sec */
timeout.tv_usec = 0; /* usec */
/* select error */
ret = select(sock + 1, &reads, 0, 0, &timeout);
if ( ret < 0 )
{
printf("select error!\n");
break;
}
/* timeout */
else if ( ret == 0 )
{
printf("timeout!\n");
break;
}
else
{
/* process function */
read(sock, ... );
accept(sock, ...);
}
.... 생략 .....
======================================================================================================
이상입니다.
감사합니다.
'프로그래밍 > C' 카테고리의 다른 글
[C] epoll 이란 (0) | 2020.12.28 |
---|---|
[C] gcc의 mcmodel 옵션 (0) | 2020.12.28 |
[C] TCP 소켓 (0) | 2020.03.09 |
[C] socket 함수 (0) | 2020.03.05 |
[C] 메모리 (0) | 2019.12.04 |