当调用execl(…)时,我得到一个errno=2。这是什么意思?我怎么知道这个errno的意思?
当前回答
在Linux上也有一个非常简洁的工具,可以立即告诉每个错误代码的含义。Ubuntu: apt-get install errno。
然后,例如,如果您想获取错误类型2的描述,只需在终端中键入errno 2。
使用errno -l可以得到一个包含所有错误及其描述的列表。比之前的海报提到的其他方法简单多了。
其他回答
我使用以下脚本:
#!/usr/bin/python
import errno
import os
import sys
toname = dict((str(getattr(errno, x)), x)
for x in dir(errno)
if x.startswith("E"))
tocode = dict((x, getattr(errno, x))
for x in dir(errno)
if x.startswith("E"))
for arg in sys.argv[1:]:
if arg in tocode:
print arg, tocode[arg], os.strerror(tocode[arg])
elif arg in toname:
print toname[arg], arg, os.strerror(int(arg))
else:
print "Unknown:", arg
有几个处理错误的有用函数。(为了说明这一点,这些都是libc内置的——我只是提供示例实现,因为有些人觉得阅读代码比阅读英语更清楚。)
#include <string.h>
char *strerror(int errnum);
/* you can think of it as being implemented like this: */
static char strerror_buf[1024];
const char *sys_errlist[] = {
[EPERM] = "Operation not permitted",
[ENOENT] = "No such file or directory",
[ESRCH] = "No such process",
[EINTR] = "Interrupted system call",
[EIO] = "I/O error",
[ENXIO] = "No such device or address",
[E2BIG] = "Argument list too long",
/* etc. */
};
int sys_nerr = sizeof(sys_errlist) / sizeof(char *);
char *strerror(int errnum) {
if (0 <= errnum && errnum < sys_nerr && sys_errlist[errnum])
strcpy(strerror_buf, sys_errlist[errnum]);
else
sprintf(strerror_buf, "Unknown error %d", errnum);
return strerror_buf;
}
Strerror返回一个字符串,描述您传递给它的错误编号。注意,这不是线程或中断安全的;可以自由地重写字符串并在下次调用时返回相同的指针。如果需要考虑这个问题,请使用strerror_r。
#include <stdio.h>
void perror(const char *s);
/* you can think of it as being implemented like this: */
void perror(const char *s) {
fprintf(stderr, "%s: %s\n", s, strerror(errno));
}
Perror将您给它的消息以及描述当前errno的字符串打印到标准错误。
可以使用strerror()为错误号获取一个人类可读的字符串。这与perror()打印的字符串相同,但如果要将错误消息格式化为标准错误输出以外的内容,则此字符串非常有用。
例如:
#include <errno.h>
#include <string.h>
/* ... */
if(read(fd, buf, 1)==-1) {
printf("Oh dear, something went wrong with read()! %s\n", strerror(errno));
}
Linux还支持显式线程安全变体strerror_r()。
当您使用strace(在Linux上)运行二进制文件时,它将输出系统调用的返回值以及错误数的含义。这可能有时对你有用。
您可以使用以下一行程序检索系统上的errno值的完整列表,而不是对所得到的任何错误代码运行perror:
cpp -dM /usr/include/errno.h | grep 'define E' | sort -n -k