Created
October 20, 2015 02:19
-
-
Save akkijp/d675d2e1e1c7388996cc to your computer and use it in GitHub Desktop.
自力で、HTTPサーバーをc言語で1から作る!
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 <stdio.h> | |
#include <stdlib.h> | |
#include <stdarg.h> | |
#include <signal.h> | |
#include <string.h> | |
typedef void (*sighandler_t)(int); | |
/* | |
* 標準エラー出力にフォーマットしたものを出力して、プロセスを終了する。 | |
* @vars (char *fmt, ...) | |
* @example log_exit("ERROR %d", 1); | |
*/ | |
static void log_exit(char *fmt, ...){ | |
va_list ap; | |
va_start(ap, fmt); | |
vfprintf(stderr, fmt, ap); | |
fputc('\n', stderr); | |
va_end(ap); | |
exit(1); | |
} | |
/* | |
* メモリを確保する。確保できなければ標準エラーに出力をして、終了する。 | |
*/ | |
static void* xmalloc(size_t sz){ | |
void *p; | |
p = malloc(sz); | |
if(!p) log_exit("faild to allocate memory."); | |
return p; | |
} | |
/* | |
* ソケット接続が切れた切れた時の一連の流れ | |
* signal_exit, trap_signal, install_signal_handlers | |
* 主に呼び出すのは **install_signal_handlers** で、 | |
* 他の関数は内部で使われる。 | |
*/ | |
static void signal_exit(int sig){ | |
log_exit("exit by signal %d", sig); | |
} | |
static void trap_signal(int sig, sighandler_t handler){ | |
int errno = 2; | |
struct sigaction act; | |
act.sa_handler = handler; | |
sigemptyset(&act.sa_mask); | |
act.sa_flags = SA_RESTART; | |
if(sigaction(sig, &act, NULL) < 0) | |
log_exit("sigaction() faild: %s", strerror(errno)); | |
} | |
static void install_signal_handlers(void){ | |
trap_signal(SIGPIPE, signal_exit); | |
} | |
int main(void){ | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment