Errno in Linux Programming

The original reference: http://mylinuxbook.com/error-handling-in-c-programming-on-linux/
This article mainly introduces the use of the global variable errno and related functions: Strerror (), strerror_r(), perror(). We can check the value of errno after calling a function to see what happens during the execution of the function. Here’s a simple example of trying to open a file that doesn’t exist read-only:

#include<stdio.h>
#include<errno.h>

int main(void)
{
    FILE *fd = NULL;

    // Reset errno to zero before calling fopen().
    errno = 0;

    // Lets open a file that does not exist   
    fd = fopen("Linux.txt","r");
    if(errno)
    {
        printf("\n fopen() failed: errno = %d\n", errno);
    }

    return 0;
}

The value of errno is set to 0 before the call of Fopen. After the call of Fopen (), we can check the value of errno to determine whether the file was successfully opened. The following is the result of execution:

fopen() failed: errno = 2
You can see that the fopen() function sets the value of errno to 2 to indicate that the file was not successfully opened. Then, errno is a number, and many times we need to see a more intuitive error message, which is strerror(), which converts the value of errno into a readable string, as shown in the following example:

#include<stdio.h>
#include<errno.h>
#include<string.h>

int main(void)
{
    FILE *fd = NULL;

    // Reset errno to zero before calling fopen().
    errno = 0;

    // Lets open a file that does not exist   
    fd = fopen("Linux.txt","r");
    if(errno)
    {
        // Use strerror to display the error string
        printf("\nThe function fopen failed due to : [%s]\n",(char*)strerror(errno));  //#1
        return -1;
    }

    return 0;
}

The output results of the program are as follows:

The function fopen failed due to: [No to The file or directory]
so we can directly see what has gone wrong, but The strerror () there is a problem, is The strerror () returns The string stored in a public area, i.e., said that if other threads also calls The function, and introduced into a different errno values, The string will be overwritten. To solve this problem, with strerro_r(), the function takes a BUF as an argument and stores the string in that BUF. Perror () also appears to output a readable error message, except that it is printed out to Stderr, and perror() replaces the output statement #1 in the above code, as follows:

perror("The function fopen failed due to");

The output page is similar:

The function fopen failed due to: No such file or directory

One thing to note: Perror does not take errno as a parameter, but instead reads the value of errno internally.

Read More: