This recipe represents the second side of the coin in the topic of error handling: error handling at a source-code level. Linux exposes its kernel features through commands, as well as through a programming API. In this recipe, we'll see how to deal with error codes and errno through a C program, to open a file.
Handling Linux code error
How to do it...
In this section, we'll see how to get the error from a system call in a C program. To do this, we'll create a program to open a non-existent file and show the details of the error returned by Linux:
- Create a new file: open_file.c.
- Edit the following code in the newly created file:
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(int argc, char *argv[])
{
int fileDesc = open("myFile.txt", O_RDONLY);
if (fileDesc == -1)
{
fprintf(stderr, "Cannot open myFile.txt .. error: %d\n",
fileDesc);
fprintf(stderr, "errno code = %d\n", errno);
fprintf(stderr, "errno meaningn = %s\n", strerror(errno));
exit(1);
}
}
- Save the file and exit (:x).
- Compile the code: gcc open_file.c.
- The preceding compilation (without parameters) will produce a binary file called a.out (which is the default name on the Linux and Unix operating systems).
How it works...
The program listed tries to open a file in reading mode. Errors are printed on standard error, through the fprintf command. By running it, the output will be as follows:
There are a couple of considerations to highlight. The program is developed by strictly following the man page of the open system call (man 2 open):
RETURN VALUES
If successful, open() returns a non-negative integer, termed a
file descriptor. It
returns -1 on failure, and sets errno to indicate the error
The developer (us, in this case) checked that the file descriptor was -1 (confirmed by fprintf) to print errno too (with code 2). What does errno 2 mean? strerror is useful exactly for this scope, to translate from errno (which is cryptic) to something the programmer (or the user) would understand.
There's more...
In Chapter 2, Revisiting C++, we'll see how C++ helps programmers by providing higher-level mechanisms, and easy-to-write and more concise code. Even if we try to minimize the interaction with the kernel API directly, in favor of the use of the C++11-14-17 higher-level mechanism, there will be cases where we'll need to check the error status. In those cases, you are invited to pay attention to error management.