Unix Network Programming Episode 5

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/myfather103/article/details/80791456

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.

猜你喜欢

转载自blog.csdn.net/myfather103/article/details/80791456