Skip to content

Instantly share code, notes, and snippets.

@doi-t
Created January 17, 2014 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doi-t/8476223 to your computer and use it in GitHub Desktop.
Save doi-t/8476223 to your computer and use it in GitHub Desktop.
send(2)のラッパー関数とマクロ定義
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
void err_msg(const char *, const char *, int, const char *, const char *, ...);
//ラッパー関数のマクロ - 本来の引数に加えて、ファイル名、関数名、行番号の情報をマクロで埋め込む
#define Send(s,b,l,f) e_Send((s),(b),(l),(f), __FILE__, __FUNCTION__, __LINE__)
ssize_t
e_Send(int sockfd, const void *buf, size_t len, int flags,
const char *file, const char *function, int line)
{
ssize_t n;
if((n = send(sockfd, buf, len, flags)) < 0){
err_msg(file, function, line, "error","[%d]=send(%d,%s,%d,%d):%s", n, sockfd, buf, len , flags, strerror(errno));
close(sockfd);
exit(1);
}
return n;
}
void
err_msg(const char *file, const char *function, int line, const char *type, const char *fmt, ...)
{
time_t timer;
time(&timer);
char *t = ctime(&timer);
t[strlen(t)-1] = '\0';
fprintf(stderr, "%s ", t); /* 現在時刻を表示 */
fprintf(stderr, "%d ", getpid()); /* プロセスIDを出力 */
fprintf(stderr, "%s %s %d %s ", file, function, line, type);
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap); /* fmtの書式に従って可変個数引数を順次呼び出す */
va_end(ap);
fprintf(stderr, " %s(%d)", strerror(errno), errno); /* エラーメッセージを出力 */
fputc('\n', stderr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment