getaddrinfo_a를 사용하여 glibc로 비동기 해결을 수행하는 방법
-
09-06-2019 - |
문제
외부 라이브러리가 필요하지 않지만 기본적으로 문서가 전혀 없는 종종 간과되는 기능입니다.
해결책
업데이트 (2010-10-11):이제 Linux 매뉴얼 페이지에 getaddrinfo_a에 대한 문서가 있으며 여기에서 찾을 수 있습니다. http://www.kernel.org/doc/man-pages/online/pages/man3/getaddrinfo_a.3.html
면책 조항으로 저는 C를 처음 접했지만 완전히 초보자는 아니라는 점을 덧붙여야 합니다. 따라서 버그나 잘못된 코딩 관행이 있을 수 있습니다. 저를 바로잡아 주세요(제 문법도 형편없습니다).
개인적으로 여기 오기 전까지는 몰랐어요 이 게시물 Adam Langley의 글에서 사용법을 설명하고 처음 사용할 때 명확하지 않을 수 있는 몇 가지 사항을 명확히 하기 위해 몇 가지 코드 조각을 제공하겠습니다.이를 사용하면 쉽게 사용할 수 있는 데이터를 다시 얻을 수 있다는 이점이 있습니다. 소켓(), 듣다() 및 기타 기능이 있으며 제대로 수행되면 ipv4/v6에 대해서도 걱정할 필요가 없습니다.
따라서 위의 링크에서 가져온 기본 사항부터 시작하려면 다음과 같이 libanl(-lanl)에 대해 링크해야 합니다.
다음은 함수 프로토타입입니다.
int getaddrinfo_a(int mode, struct gaicb *list[], int ent,
struct sigevent *);
- 그만큼 방법 비동기 조회의 경우 GAI_WAIT(원하는 것이 아닐 수도 있음) 및 GAI_NOWAIT 중 하나입니다.
- 그만큼 gaicb 인수는 조회할 호스트 배열을 허용합니다. 엔트 배열에 포함된 요소 수를 지정하는 인수
- 그만큼 시게벤트 우리가 어떻게 알림을 받을지 함수에 알려줄 책임이 있습니다. 이에 대한 자세한 내용은 잠시 후
gaicb 구조체는 다음과 같습니다:
struct gaicb {
const char *ar_name;
const char *ar_service;
const struct addrinfo *ar_request;
struct addrinfo *ar_result;
};
getaddrinfo에 익숙하다면 이러한 필드는 다음과 같이 대응됩니다.
int getaddrinfo(const char *node, const char *service,
const struct addrinfo *hints,
struct addrinfo **res);
노드는 ar_name 필드이고, service는 포트이며, 힌트 인수는 ar_request 멤버에 해당하고 결과는 나머지에 저장됩니다.
이제 sigevent 구조를 통해 알림을 받을 방법을 지정합니다.
struct sigevent {
sigval_t sigev_value;
int sigev_signo;
int sigev_notify;
void (*sigev_notify_function) (sigval_t);
pthread_addr_t *sigev_notify_attributes;
};
- _sigev_notify_를 SIGEV_NONE으로 설정하여 알림을 무시할 수 있습니다.
- sigev_notify를 SIGEV_SIGNAL로 설정하고 sigev_signo를 원하는 신호로 설정하여 신호를 트리거할 수 있습니다.실시간 신호(SIGRTMIN-SIGRTMAX, 항상 매크로와 추가를 통해 사용하세요 SIGRTMIN+2 등) sigev_value.sival_ptr 또는 sigev_value.sival_int 멤버 각각의 포인터나 값을 전달할 수 있습니다.
- sigev_notify를 SIGEV_NONE으로 설정하여 새 스레드에서 콜백을 요청할 수 있습니다.
따라서 기본적으로 호스트 이름을 검색하려면 ar_name을 호스트로 설정하고 다른 모든 항목을 다음으로 설정합니다. 없는, 호스트에 연결하려면 ar_name 및 ar_service를 설정하고, 서버를 생성하려면 ar_service 및 ar_result 필드를 지정합니다.물론 ar_request 멤버를 원하는 대로 사용자 정의할 수 있습니다. 남자 getaddrinfo 더 많은 정보를 위해서.
select/poll/epoll/kqueue가 포함된 이벤트 루프가 있는 경우 다음을 사용할 수 있습니다. 신호 편의상.Signalfd는 다음과 같은 일반적인 이벤트 폴링 메커니즘을 사용할 수 있는 파일 설명자를 생성합니다.
#define _GNU_SOURCE //yes this will not be so standardish
#include <netdb.h>
#include <signal.h>
#include <sys/signalfd.h>
void signalfd_setup(void) {
int sfd;
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGRTMIN);
sigprocmask(SIG_BLOCK, &mask, NULL); //we block the signal
sfd = signalfd(-1, &mask, 0);
//add it to the event queue
}
void signalfd_read(int fd) {
ssize_t s;
struct signalfd_siginfo fdsi;
struct gaicb *host;
while((s = read(fd, &fdsi, sizeof(struct signalfd_siginfo))) > 0){
if (s != sizeof(struct signalfd_siginfo)) return; //thats bad
host = fdsi.ssi_ptr; //the pointer passed to the sigevent structure
//the result is in the host->ar_result member
create_server(host);
}
}
void create_server(struct gaicb *host) {
struct addrinfo *rp, *result;
int fd;
result = host->ar_result;
for(rp = result; rp != NULL; rp = rp->ai_next) {
fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
bind(fd, rp->ai_addr, rp->ai_addrlen);
listen(fd, SOMAXCONN);
//error checks are missing!
freeaddrinfo(host->ar_request);
freeaddrinfo(result);
//you should free everything you put into the gaicb
}
}
int main(int argc, char *argv[]) {
struct gaicb *host;
struct addrinfo *hints;
struct sigevent sig;
host = calloc(1, sizeof(struct gaicb));
hints = calloc(1, sizeof(struct addrinfo));
hints->ai_family = AF_UNSPEC; //we dont care if its v4 or v6
hints->ai_socktype = SOCK_STREAM;
hints->ai_flags = AI_PASSIVE;
//every other field is NULL-d by calloc
host->ar_service = "8888"; //the port we will listen on
host->ar_request = hints;
sig.sigev_notify = SIGEV_SIGNAL;
sig.sigev_value.sival_ptr = host;
sig.sigev_signo = SIGRTMIN;
getaddrinfo_a(GAI_NOWAIT, &host, 1, &sig);
signalfd_setup();
//start your event loop
return 0;
}
물론 이 작업에도 간단한 신호 처리기를 사용할 수 있습니다. 남자 시그액션 더 많은 정보를 위해서.