32、深入理解计算机系统笔记,Unix下处理错误的风格

1、unix风格的错误机制下,当函数,如wait执行出错后,it returns -1

and sets the global variable errno to an error code that indicate the cause of the error.如果成功,则返回有用的结果。

if ((pid = wait(NULL)) < 0) {

fprintf(stderr, "wait error: %s\n", strerror(errno));

exit(0);

}

The strerror function returns a text description for a particular value of errno

2、Posix-style

    执行错误时,通过返回的错误码来进行判断。成功则返回0

if ((retcode = pthread_create(&tid, NULL, thread, NULL)) != 0) {

fprintf(stderr, "pthread_create error: %s\n", strerror(retcode));

exit(0);

}

3、DNS-style

These functions return a NULL pointer on failure and set the global h errno variable.

if ((p = gethostbyname(name)) == NULL) {

fprintf(stderr, "gethostbyname error: %s\n:", hstrerror(h_errno));

exit(0);

}

4、处理错误的封装函数

void unix_error(char *msg) /* unix-style error */

{

fprintf(stderr, "%s: %s\n", msg, strerror(errno));

exit(0);

}

void posix_error(int code, char *msg) /* posix-style error */

{

fprintf(stderr, "%s: %s\n", msg, strerror(code));

exit(0);

}

void dns_error(char *msg) /* dns-style error */

{

fprintf(stderr, "%s: %s\n", msg, hstrerror(h_errno));

exit(0);

}

posted @ 2011-07-30 13:33  浪里飞  阅读(480)  评论(0编辑  收藏  举报