Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Linux System Programming Techniques

You're reading from   Linux System Programming Techniques Become a proficient Linux system programmer using expert recipes and techniques

Arrow left icon
Product type Paperback
Published in May 2021
Publisher Packt
ISBN-13 9781789951288
Length 432 pages
Edition 1st Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
Jack-Benny Persson Jack-Benny Persson
Author Profile Icon Jack-Benny Persson
Jack-Benny Persson
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Chapter 1: Getting the Necessary Tools and Writing Our First Linux Programs 2. Chapter 2: Making Your Programs Easy to Script FREE CHAPTER 3. Chapter 3: Diving Deep into C in Linux 4. Chapter 4: Handling Errors in Your Programs 5. Chapter 5: Working with File I/O and Filesystem Operations 6. Chapter 6: Spawning Processes and Using Job Control 7. Chapter 7: Using systemd to Handle Your Daemons 8. Chapter 8: Creating Shared Libraries 9. Chapter 9: Terminal I/O and Changing Terminal Behavior 10. Chapter 10: Using Different Kinds of IPC 11. Chapter 11: Using Threads in Your Programs 12. Chapter 12: Debugging Your Programs 13. Other Books You May Enjoy

Error handling and errno

Most of the system call functions in Linux and other UNIX-like systems set a special variable called errno when an error occurs. This way, we get a general error code from the return value (often -1) and then more specific information about what went wrong by looking at the errno variable.

In this recipe, we'll learn what errno is, how to read values from it, and when it is set. We'll also see an example use case of errno. Learning about errno is imperative to system programming, primarily since it's used in conjunction with system calls.

The next few recipes in this chapter are closely tied to this recipe. In this recipe, we'll learn about errno; in the following three recipes, we'll learn how to interpret the error codes we get from errno and print human-readable error messages.

Getting ready

You'll need the same components for this recipe that we used in the previous one; that is, the GCC compiler, the Make tool, and the POSIX Programmer's Manual, all of which we have already installed. If not, see Chapter 1, Getting the Necessary Tools and Writing Our First Linux Programs, and the Getting information about Linux- and UNIX-specific header files section of Chapter 3, Diving Deep into C in Linux.

How to do it…

In this recipe, we'll continue building on simple-touch-v2.c from the first recipe in this chapter. Here, we'll extend it so that it prints some more useful information if it can't create a file:

  1. Write the following code into a file and save it as simple-touch-v3.c. In this version, we'll use the errno variable to check if the error is caused by a permission error (EACCES) or some other, unknown error. The changed code has been highlighted here:
    #include <stdio.h>
    #include <fcntl.h>
    #include <string.h>
    #include <errno.h>
    #include <linux/limits.h>
    int main(int argc, char *argv[])
    {
       char filename[PATH_MAX] = { 0 };
       if (argc != 2)
       {
          fprintf(stderr, "You must supply a filename "
             "as an argument\n");
          return 1;
       }
       strncpy(filename, argv[1], sizeof(filename)-1);
       if ( creat(filename, 00644) == -1 )
       {
          fprintf(stderr, "Can't create file %s\n", 
             filename);
          if (errno == EACCES)
          {
             fprintf(stderr, "Permission denied\n");
          }
          else
          {
             fprintf(stderr, "Unknown error\n");
          }
          return 1;
       }
       return 0;
    }
  2. Let's compile this version:
    $> make simple-touch-v3
    gcc -Wall -Wextra -pedantic -std=c99    simple-touch-v3.c   -o simple-touch-v3
  3. Finally, let's run the new version. This time, the program gives us more information about what went wrong. If it's a permission error, it will tell us that. Otherwise, it will print Unknown error:
    $> ./simple-touch-v3 asdf
    $> ls -l asdf
    -rw-r--r-- 1 jake jake 0 okt 13 23:30 asdf
    $> ./simple-touch-v3 /asdf
    Can't create file /asdf
    Permission denied
    $> ./simple-touch-v3 /non-existent-dir/hello
    Can't create file /non-existent-dir/hello
    Unknown error

How it works…

The first difference we'll notice in this version is that we now include a header file called errno.h. This file is required if we wish to use the errno variable and the many error macros. One of these macros is EACCES, which we used in our new version.

The next difference is that we now use sizeof(filename)-1 instead of PATH_MAX-1 for the size argument to strncpy(). This was something we learned in the previous recipe.

Then, we have the if (errno == EACCES) line, which checks the errno variable for EACCES. We can read about these macros, such as EACCES, in both man errno.h and man 2 creat. This particular macro means permission denied.

When we use errno, we should first check the return value from the function or system call, as we did here with the if statement around creat(). The errno variable is just like any other variable, meaning that it isn't cleared after the system call. If we were to check errno directly, before checking the function's return value, errno could contain an error code from a previous error.

In our version of touch, we only handle this specific error. Next, we have an else statement, which catches all other errors and prints an Unknown error message.

In Step 3, we generated an Unknown error message by trying to create a file in a directory that doesn't exist on our system. In the next recipe, we'll extend our program so that it can take more macros into account.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image