Book Image

Hands-On System Programming with C++

By : Dr. Rian Quinn
Book Image

Hands-On System Programming with C++

By: Dr. Rian Quinn

Overview of this book

C++ is a general-purpose programming language with a bias toward system programming as it provides ready access to hardware-level resources, efficient compilation, and a versatile approach to higher-level abstractions. This book will help you understand the benefits of system programming with C++17. You will gain a firm understanding of various C, C++, and POSIX standards, as well as their respective system types for both C++ and POSIX. After a brief refresher on C++, Resource Acquisition Is Initialization (RAII), and the new C++ Guideline Support Library (GSL), you will learn to program Linux and Unix systems along with process management. As you progress through the chapters, you will become acquainted with C++'s support for IO. You will then study various memory management methods, including a chapter on allocators and how they benefit system programming. You will also explore how to program file input and output and learn about POSIX sockets. This book will help you get to grips with safely setting up a UDP and TCP server/client. Finally, you will be guided through Unix time interfaces, multithreading, and error handling with C++ exceptions. By the end of this book, you will be comfortable with using C++ to program high-quality systems.
Table of Contents (16 chapters)

Learning about the tail file example

In this example, we will create a simple program to tail a file. The goal of this example is to mimic the behavior of tail -f -n0, which outputs new additions to a file. The -f argument tells the tail to follow the file and -n0 tells tail to only output to stdout new additions.

The first step is to define the mode we plan to use when opening the file we are tailing, as follows:

constexpr auto mode = std::ios::in | std::ios::ate;

In this case, we will open the file as read-only, and move the read pointer to the end of the file on open.

The next step is to create a tail function that watches for changes to a file and outputs the changes to stdout, as follows:

[[noreturn]] void
tail(std::fstream &file)
while (true) {
while(!file.eof()) {
auto pos = file.tellg();

std::string buf;