Linux C error handling, errno and perror

By | December 16, 2019

If you have Java or .Net programming background you used to be familiar with exception which generated in runtime if something is going wrong with code execution. Linux C does not provide direct support to runtime error handling or exception handling. Usually code developer has to check return values from the functions. Generally C function calls return minus one or not zero value in case of an error. So you need to test the return value with ‘if statement’ for example.
The numerical value of the last error is set in global variable errno. The error codes are defined in header file errno.h.
For instance the errors from 1 to 14 are:


#define EPERM    1    /* Operation not permitted */
#define ENOENT   2    /* No such file or directory */
#define ESRCH    3    /* No such process */
#define EINTR    4    /* Interrupted system call */
#define EIO      5    /* Input/output error */
#define ENXIO    6    /* Device not configured */
#define E2BIG    7    /* Argument list too long */
#define ENOEXEC  8    /* Exec format error */
#define EBADF    9    /* Bad file descriptor */
#define ECHILD   10   /* No child processes */
#define EDEADLK  11   /* Resource deadlock avoided */
                      /* 11 was EAGAIN */
#define ENOMEM   12   /* Cannot allocate memory */
#define EACCES   13   /* Permission denied */
#define EFAULT   14   /* Bad address */

Here is an example of error handling program:


#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
   int fd = open("/not_valid_dir/test", O_WRONLY | O_CREAT,
      S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH /* 0x644 */);
   if(fd<0)
   {
      printf("Error code: %d\n", errno);
      perror("File \"test\"");
      return -1;
   } else {
      write(fd, (const char*)"some text", 9);
      close(fd);
      return 0;
   }
}

Function perror prints system error message corresponding to the last error which occurred.

The result of execution:


# g++ -o error error.cpp
# ./error
Error code: 2
File “test”: No such file or directory
#

By the way printf and perror write to the different streams, printf writes to stdio stream but perror outputs to sdterr one. It is good visible when stdio and stderr outputs are redirected to files (file a.a for stdio and file b.b for strerr):


# ./error > a.a
File “test”: No such file or directory
# cat a.a
Error code: 2
# ./error 2> b.b
Error code: 2
# cat b.b
File “test”: No such file or directory

To redirect both stdio and stderr to the same file, however the order of messages is changed, stderr is saved first:


# ./error > c.c 2>&1
# cat c.c
File “test”: No such file or directory
Error code: 2

Leave a Reply

Your email address will not be published. Required fields are marked *