Unix Network Programming Episode 5

Error Handling: Wrapper Functions

Since terminating on an error is the common case, we can shorten our programs by defining a wrapper function that performs the actual function call, tests the return value, and terminates on an error. The convention we use is to capitalize the name of the function, as in

sockfd = Socket(AF_INET, SOCK_STREAM, 0);
int Socket(int family, int type, int protocol)
{
    int n;

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

Our wrapper function for the socket function.

Whenever you encounter a function name in the text that begins with an uppercase letter, that is one of our wrapper functions. It calls a function whose name is the same but begins with the lowercase letter.

We will find that thread functions do not set the standard Unix errno variable when an error occurs; instead, the errno value is the return value of the function. This means that every time we call one of the pthread_ functions, we must allocate a variable, save the return value in that variable, and then set errno to this value before calling err_sys. To avoid cluttering the code with braces, we can use C’s comma operator to combine the assignment into errno and the call of err_sys into a single statement, as in the following:

int n;

if((n=pthread_mutex_lock(&ndone_mutex))!=0)
    errno=n, err_sys("pthread_mutex_lock error");

Alternately, we could define a new error function that takes the system’s error number as an argument. But, we can make this piece of code much easier to read as just

Pthread_mutex_lock(&ndone_mutex);

by defining our own wrapper function

void Pthread_mutext_lock(pthread_mutext_t *mptr)
{
    int n;

    if((n=pthread_mutext_lock(mptr))==)
        return ;

    errno=n;
    err_sys("pthread_mutex_lock error");
}

With careful C coding, we could use macros instead of functions, providing a little run-time efficiency, but these wrapper functions are rarely the performance bottleneck of a program.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值