socket编程中错误处理封装函数

【socket编程中错误处理封装函数】君不见长松卧壑困风霜,时来屹立扶明堂。这篇文章主要讲述socket编程中错误处理封装函数相关的知识,希望能为你提供帮助。
系统调用不能保证每次都成功,需要进行必要的出错处理,这样才能保证程序逻辑运行正常和出错的时候迅速找到出错的原因。
socket编程中的一些错误,写在主函数中显得代码繁琐复杂,下面将这些错误处理包装成了新的函数,做成一个模块。

(1)myerr.h

#ifndef __MYERR_H_
#define __MYERR_H_
void perr_exit(const char *s);
int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr);
int Bind(int fd, const struct sockaddr *sa, socklen_t salen);
int Connect(int fd, const struct sockaddr *sa, socklen_t salen);
int Listen(int fd, int backlog);
int Socket(int family, int type, int protocol);
ssize_t Read(int fd, void *ptr, size_t nbytes);
ssize_t Write(int fd, const void *ptr, size_t nbytes);
int Close(int fd);
ssize_t Readn(int fd, void *vptr, size_t n);
ssize_t Writen(int fd, const void *vptr, size_t n);
ssize_t my_read(int fd, char *ptr);
ssize_t Readline(int fd, void *vptr, size_t maxlen);
#endif

(2)myerr.c
#include < stdlib.h>
#include < errno.h>
#include < sys/socket.h>
void perr_exit(const char *s)

perror(s);
exit(1);

int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr)

int n;
again:
if ( (n = accept(fd, sa, salenptr)) < 0)
if ((errno == ECONNABORTED) || (errno == EINTR))
goto again;
else
perr_exit("accept error");

return n;

int Bind(int fd, const struct sockaddr *sa, socklen_t salen)

int n;
if ((n = bind(fd, sa, salen)) < 0)
perr_exit("bind error");
return n;

int Connect(int fd, const struct sockaddr *sa, socklen_t salen)

int n;
if ((n = connect(fd, sa, salen)) < 0)
perr_exit("connect error");
return n;

int Listen(int fd, int backlog)

int n;
if ((n = listen(fd, backlog)) < 0)
perr_exit("listen error");
return n;

int Socket(int family, int type, int protocol)

int n;
if ( (n = socket(family, type, protocol)) < 0)
perr_exit("socket error");
return n;

ssize_t Read(int fd, void *ptr, size_t nbytes)

ssize_t n;
again:
if ( (n = read(fd, ptr, nbytes)) == -1)
if (errno == EINTR)
goto again;
else
return -1;

return n;

ssize_t Write(int fd, const void *ptr, size_t nbytes)

ssize_t n;
again:
if ( (n = write(fd, ptr, nbytes)) == -1)
if (errno == EINTR)
goto again;
else
return -1;

return n;

int Close(int fd)

int n;
if ((n = close(fd)) == -1)
perr_exit("close error");
return n;

ssize_t Readn(int fd,

    推荐阅读