当调用execl(…)时,我得到一个errno=2。这是什么意思?我怎么知道这个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()。
其他回答
它的意思是:
未找到文件或目录。
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(int i, char *c[]) {
if (i != 2)
fprintf(stderr, "Usage: perror errno\n");
else {
errno = atoi(c[1]);
perror("");
}
exit(0);
}
适用于Solaris。 Cc perror.c -o perror <<使用这一行来编译它
可以使用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()。
有几个处理错误的有用函数。(为了说明这一点,这些都是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的字符串打印到标准错误。
在shell中输入sudo apt-get install moreutils,然后,一旦安装完成,输入errno 2。您还可以对所有错误编号使用errno -l,或者通过将其输送到grep只查看文件编号,如下所示:errno -l | grep file。