本文介绍了为什么要使用'errno'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Technion 的一名 CS 学生,我刚刚了解了 errno 变量和 c 风格的函数调用.这让我想知道,如果 c 风格的系统调用使用寄存器来返回一个值,为什么有人应该使用 errno 呢?

I'm a CS student at the Technion, I have just learned of errno variable and c-style function calls.This makes me wonder, if c-style syscalls use registers to return a value, why should anyone use errno at all?

推荐答案

使用 errno 的主要原因是为了提供有关错误情况的更多信息.

The main reason for using errno is to give more information about the error condition.

这在函数的大多数(甚至所有)可能返回值实际上是有效返回值的情况下特别有用.

This is especially useful in situations where most (or even all) possible return values of a function are actually valid return values.

考虑 fopen() 函数,它返回一个指向 FILE 的指针.每个可能的返回值也是一个有效的返回值,除了 NULL.所以 fopen() 在失败时返回 NULL.但是你无法判断究竟是什么导致了函数失败.因此,fopen() 使用 errno 来表示确切的错误条件,即文件不存在,或者您无权读取它,或者系统内存不足,或者其他什么.

Consider the fopen() function, which returns a pointer to a FILE. Every possible return value is also a valid return value, except NULL. So fopen() returns NULL on failure. But then you can't tell what exactly made the function fail. Hence, fopen() uses errno to denote the exact error condition, i.e. the file doesn't exist, or you don't have permission to read it, or the system is out of memory, or whatever.

您可以将 errno 视为一个全局变量(在线程流行之前它曾经是).现在,errno 通常是一个宏,它封装了返回错误条件的函数调用.但这只是 C 实现线程特定全局变量的方式.

You can think of errno as a global variable (which it used to be until threads became popular). Nowadays, errno is usually a macro wrapping a function call returning the error condition. But this is just C's way of implementing thread-specific global variables.

errno 的替代方案不太舒服:

The alternatives to errno are less comfortable:

您可以提供一个带有指向 int 的指针的函数,并且该函数可以在那里存储其错误条件.strtod() 是这种技术的一个很好的例子.但这使得 API 更加复杂,因此不太理想.另外,它强制程序员定义一个新的int,如果你不关心函数是否失败,这很烦人.

You could supply a function with a pointer to an int, and the function can store its error condition there. strtod() is a good example of this technique. But this makes the API more complicated and hence less desirable. Also, it forces the programmer to define a new int, which is annoying if you don't care if the function fails.

在允许多个返回值(并且没有异常)的语言中,返回两个值是很常见的:一个用于实际结果,另一个用于表示错误条件.在 Go 等语言中,您会看到如下代码:

In languages that allow more than one return value (and don't feature exceptions), it's common to return two values: one for the actual result and another to denote the error condition. In languages like Go, you see code like the following:

result, ok = foo();
if (ok) {
    // handle error denoted by "ok"
}

不要相信那些声称 errno 是一种旧"技术,因此应该避免的人.您正在编程的机器比 errno 甚至 C 都要古老得多,而且从来没有人抱怨过这一点.

Don't trust people who claim that errno is an "old" technique and hence to be avoided. The machine you're programming is far older than errno or even C, and nobody has ever complained about that.

这篇关于为什么要使用'errno'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:42