我可以使用strerror()获得errno值的文本表示形式,比如使用fopen()。如果我使用open() Linux系统调用而不是CRT函数,它也会在失败时设置errno值。将strerror()应用于此errno值是否正确?如果没有,是否有与strerror()相同的Linux系统调用?
发布于 2011-04-16 10:48:50
是
是
里面有perror
if (-1 == open(....))
{
perror("Could not open input file");
exit(255)
}发布于 2011-04-16 11:15:00
是的,您的代码可能是(未经测试的)如下所示:
#include <stdio.h>
#include <errno.h>
#include <string.h> // declares: char *strerror(int errnum);
FILE *
my_fopen ( char *path_to_file, char *mode ) {
FILE *fp;
char *errmsg;
if ( fp = fopen( path_to_file, mode )) {
errmsg = strerror( errno ); // fopen( ) failed, fp is set to NULL
printf( "%s %s\n", errmsg, path_to_file );
}
else { // fopen( ) succeeded
...
}
return fp; // return NULL (failed) or open file * on success
}发布于 2022-09-24 10:56:11
大多数Linux系统调用都由C库例程封装。open()系统调用实际上是C库中定义的函数,它调用内核的实际open()系统调用。
errno是一个由C库而不是由内核定义和管理的变量。它是在系统调用返回时设置的,其中包含内核返回的错误代码。
例如,在GNU库中,open()在sysdeps/unix/sysv/linux/open.c中定义为:
int
__libc_open (const char *file, int oflag, ...)
{
int mode = 0;
if (__OPEN_NEEDS_MODE (oflag))
{
va_list arg;
va_start (arg, oflag);
mode = va_arg (arg, int);
va_end (arg);
}
return SYSCALL_CANCEL (openat, AT_FDCWD, file, oflag, mode);
}
libc_hidden_def (__libc_open)
weak_alias (__libc_open, __open)
libc_hidden_weak (__open)
weak_alias (__libc_open, open)底部宏建立了__libc_open()和open()之间的等价关系。
SYSCALL_CANCEL()宏调用实际的系统调用(即openat()),如果出现任何错误情况,则使用错误代码设置errno。
https://stackoverflow.com/questions/5685973
复制相似问题