Introduction
Errors are issues or flaws in the program that cause it to behave abnormally. These mistakes can be made even by skilled coders. Without knowing the type or cause of the error, it is very hard to solve the error. That is why we have a whole bunch of error codes available to us. Error codes are the integer value that tells us what kind of error we are getting in our code or program.
This blog will explain the many types of Linux error codes, and we will also see how we can retrieve error information using the error code.
Linux Errors
Linux is made using the C programming language. Most of the code for Linux Kernel is written in C Programming language. Error management is not directly supported by the C programming language. If an error occurs while running the C program, a number is returned that specifies the error type.
There is a variable, namely 'errorno', available in C language that can be used to identify the type of error. We can use the value of this variable to handle the error efficiently.
Let’s have a look at how we can use the value of ‘errno’ variable to get the error information.
Getting Error information
We must include the header file 'errno.h' to use the external variable errno. The "errno" variable is defined in the "error.h" header file. System calls and library routines set the errno variable when an error occurs.
In C programming, there are two different functions available perror and strerror, which can be used to print the description of the error and get the error code.
Let’s look at how we can use both available functions to get error details.
Code
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int errno;
int main () {
FILE *file = fopen("CodingNinja.txt", "rb"); // opening the file
if (file == NULL) {
printf("Error code: %d\n", errno);
perror("Error Description");
} else {
fclose(file);
}
return 0;
}
Output
Error code: 2
Error Description: No such file or directory
In the above program, we are trying to open a file that does not exist on our system. Now, without knowing the error code, it would be hard to figure out what causes the error.
The value of errno is set to 2, which represents that the file does not exist. There are more than 100 such error codes, each representing a different type of error.
Let’s have a look at some of the error code and their cause.