简体   繁体   中英

errno, strerror and Linux system calls

I can use strerror() to get text representation of errno value after using CRT functions, like fopen() . If I use open() Linux system call instead of CRT function, it also sets errno value when it fails. Is this correct to apply strerror() to this errno value? If not, is there some Linux system call, which does the same as strerror() ?

Yes, and your code might be something like (untested) this:

   #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
   }

Yes

Yes

In there is perror

if (-1 == open(....))
{
    perror("Could not open input file");
    exit(255)
}

Most of the Linux system calls are encapsulated by C library routines. open() system call is actually a function defined in the C library which calls the actual open() system call of the kernel.

errno is a variable defined and managed by the C library, not by the kernel. It is set upon the return of the system call with the error code returned by the kernel.

As an example, in the GNU C library, open() is defined in sysdeps/unix/sysv/linux/open.c as:

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)

The bottom macros establish a equivalence between __libc_open() and open() .
The SYSCALL_CANCEL() macros invokes the actual system call (which is openat() ) and sets errno with the error code if any error condition occured.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM