Reader small image

You're reading from  C++ Programming for Linux Systems

Product typeBook
Published inSep 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805129004
Edition1st Edition
Languages
Right arrow
Authors (2):
Desislav Andreev
Desislav Andreev
author image
Desislav Andreev

Desislav Andreev is a software engineer with a PhD in artificial intelligence systems and quantum machine learning. He has several publications in software engineering and AI applications. For his 10 years in the field he has a demonstrated history of working in automotive software engineering and in the area of the higher education. He is skilled in system and software architectures, operating systems, C and C++ development, autonomous driving and computer graphics. He is currently working as a Lead C++ Developer in VMware, developing its core software functionalities. He is also a lecturer at the Technical University of Sofia. He was previously a Technical Professional and software architect in the CRE and ADAS departments of Visteon Corporation, working closely with both OEMs and development teams.
Read more about Desislav Andreev

Stanimir Lukanov
Stanimir Lukanov
author image
Stanimir Lukanov

Stanimir Lukanov is a C++ expert, software tech lead and architect at VMWare. He has more than 15 years of professional experience in writing efficient and robust C++ enterprise code. Stanimir is a member of the Bulgarian National Body which is part of The C++ Standards Committee (JTC1/SC22/WG21). His interests are in the area of software security for distributed enterprise software systems. Since 2017 he has worked at VMWare where he currently leads a team which develops core security functionality in one of the major products in the company's portfolio. Before joining VMWare he held the position of senior software engineer at Visteon Corporation and Johnson Controls. He was responsible for defining software architecture, making code reviews, leading C++ training and delivering fast and robust C++ code for real-time automotive embedded systems.
Read more about Stanimir Lukanov

View More author details
Right arrow

Preface

Greetings, dear reader! You are among friends. Welcome to this journey of advanced skills, unexpected surprises, cunning knowledge, and novel programming tools. Suppose you are an experienced software engineer who knows how to write quality code and is aware of some build and operating systems. You have also met several computer architectures and fixed one or two bugs. And how about the following: You are a student who just learns how to do the job of a software engineer. You want to be a good professional someday. And you want to be the expert, whom others call, whenever the software behaves unpredictably. Or you just have picked up this book out of initial interest, still not knowing what to expect. Then perfect!

We challenge you to remember any situations in your practice, where, to this day, you have no explanation of what happened. No, we do not mean the supernatural – although this topic is rather arcane. We speak about the system and how we conduct its behavior as professional engineers. Our code is just an instrument that tells the machine what to do. So, let’s say you have remembered that one bug that has been bugging you for some time – how do you proceed? What if it stands between you and your next promotion? How about when it disappoints a client that is important to you? Or you just want to impress your teacher. We get you! We are there, too.

Do not be fooled, though. We give you the opportunity to enrich the way you engineer through some fundamental pointers, but we do not have all the answers. We strongly believe that changing the way you see how code works will make you a more robust expert, no matter your professional field. And you should care because the world of technology is rapidly advancing. It is impossible to keep up with every innovation, algorithm, language, operating system, and architecture. But you could start asking yourself the right questions at the right moment. You have the possibility to know how to optimize further, design better, validate your environment, and encourage yourself to understand your own work thoroughly.

We challenge you again. This time to be more self-aware and efficient through our experience and expertise. There are some sophisticated real-world challenges that we so impatiently want to share with you. Please remember, it will take you some time. As friends, we hope you enjoy this book and share the exciting parts with others. Chop-chop... Let’s go!

Who this book is for

This book is for programmers and developers who want to boost their programming knowledge in C++ for Linux and Unix-based operating systems. Whether you are a beginner looking to learn how to use C++ in such an environment or an experienced programmer looking to explore the latest C++20 features applicable to system programming, you’ll find this book helpful.

What this book covers

Chapter 1, Getting Started with the Linux Systems and the POSIX Standard, introduces the reader to the reasoning behind the existence of different operating systems. The Linux specifics are discussed, and the reader proceeds to the fundamentals of Unix-based OS programming. The kernel space and user spaces are mentioned as the System Call Interface is explained thoroughly. Afterward, we use this opportunity to present POSIX and some standard function calls in order to let the reader grasp the benefits of the system programming.

Chapter 2, Learning More about Process Management, expands on learnings from the previous chapter and states that if the operating system is the main resource manager, then the process is the main resource user. It does so through a routine, which could get complex and needs to be well analyzed. Therefore, the chapter goes through the main process’s life cycle - its startup, running, and final states. The nature of the thread is presented as well. We go through the OS’s scheduling algorithms as well. A sample C++ application is introduced and its main() function is discussed as an entry point. In addition, different ways to initiate a process are presented: fork(), vfork(), and exec(). Other fundamental functions such as wait(), exit(), pthread_create(), and pthread_join() are discussed as well.

Chapter 3, Navigating through the Filesystems, shows how the file is the basic resource representation in Linux - both for data and access to I/O devices. This abstraction allows the user to manipulate streams or store data in the same manner, through the same system interfaces. The file system structure - metadata and inodes, is discussed. Examples of C++ file system operations are presented to the reader. We use this opportunity to introduce the pipes as an initial instrument for inter-process communication. The string_view C++20 object is offered as well. At the end, we mention signal handling as it will be required for later chapters.

Chapter 4, Diving Deep into the C++ Object, guides the reader through some core C++ features like the process of object creation and its initialization. We discuss lifetime object problems, temporaries, RVO, RAII pattern, and C++20. We also cover function objects and lambda expressions together with their specifics and guidance on how to use them. Next, we will get deeper into lambdas. In the end, we will focus on some specific examples of how to use lambdas in STL and multithreading.

Chapter 5, Handling Errors with C++, explores the different kinds of error reporting in C++ programming for Unix-based operating systems, such as error codes, exceptions, and asserts. We will discuss the best practices in exception handling and exception manipulation and what happens with uncaught exceptions in the system. We will discuss the exception specifications and why we prefer the noexcept keyword. We will go through the performance impact when using exceptions and the mechanics behind them. Next, we will discuss how we can use std::optional to handle errors. At the end, we will discuss what std::uncaught_exceptions functionality provides.

Chapter 6, Concurrent System Programming with C++, discusses the fundamentals and the theory behind processes and threads in Unix-based operating systems. We will go through the changes in the memory model of C++ in order to natively support concurrency. We will get acquainted with the C++ primitives which enable multithreading support - thread, jthread, and task. Next, we will learn how to synchronize the execution of parallel code using C++ synchronization primitives. We will also investigate what STL provides in the direction of parallel algorithms. In the end, we will learn how to write lock-free code.

Chapter 7, Proceeding with Inter-process Communication, guides readers through the basic IPC mechanisms in the Linux environment (as they already have the impression of the multithreading’s challenges). It is important that the processes are able to communicate with each other easily, therefore, we go quickly through message queues. They allow the exchange of data without blocking processes. We will spend some time discussing synchronization mechanisms – semaphore and mutex- and then proceed with the shared memory. It provides quick access to some data and, at the same time, allows heterogeneous systems to have a common point for data exchange. At last, the sockets are frequently used, but mainly for their possibility to allow communication between computer systems on the network.

Chapter 8, Using Clocks, Timers, and Signals in Linux, introduces the signals and timers in Unix-based operating systems. We will initially present how the signaling system works and how the user can effectively manage the time of operations. We will cover what C++ language provides as functionality to handle clocks and timers. We will introduce the standard time API, std::chrono, predefined clocks and times. Next, we will cover how to use them correctly and what to expect from them. Next, we will focus on the duration capabilities that the standard provides and user-defined clocks. Ultimately, we will cover the calendar and time zone libraries introduced in C++20.

Chapter 9, Understanding the C++ Memory Model, explores some new C++20 features. It guides the reader through some crucial remarks on how and why to manage dynamic resources. It proceeds with a discussion on the conditional variables and mutex usages, as well as lazy initialization and cache friendliness. An introduction to the C++ memory order follows as we discuss ways to choose from different synchronization mechanisms. The spinlock/ticketlock techniques are also presented.

Chapter 10, Using Coroutines in C++ for System Programming, talks about coroutines, an already existing term with implementations in some programming languages, but now they are introduced in C++20. They are described as stackless functions suspended during execution and resumed later. The chapter discusses those exact valuable features in the area of system programming. Their disadvantages are also discussed, for example, keeping the suspended coroutine state on the heap. Some practical usages are presented.

To get the most out of this book

Some familiarity with the basics of the C++ language and POSIX programming in C language is required before starting with this book. Prior knowledge of the fundamentals of Linux and Unix will be helpful but not necessary.

Software covered in the book

Operating system requirements

C++20

Linux Mint 21

GCC12.2

godbolt.org

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors in copying and pasting code.

Each chapter has its respective Technical requirements. All examples are run through them. The code is system-dependent, so it might not work directly in your environment.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/C-Programming-for-Linux-Systems. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “The example uses the open() and close() POSIX functions, which try to open and close a file from the filesystem of our Linux test environment.”

A block of code is set as follows:

if (ecode.value() == EEXIST)

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

std::for_each(v1.begin(), v1.end(),
                  [&mean, sum{0.0}, count{0}, text](const double& val) mutable

Any command-line input or output is written as follows:

$ ./test

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at customercare@packtpub.com and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read C++ Programming for Linux Systems, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

  1. Scan the QR code or visit the link below

https://packt.link/free-ebook/9781805129004

  1. Submit your proof of purchase
  2. That’s it! We’ll send your free PDF and other benefits to your email directly
lock icon
The rest of the chapter is locked
You have been reading a chapter from
C++ Programming for Linux Systems
Published in: Sep 2023Publisher: PacktISBN-13: 9781805129004
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.
undefined
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 $15.99/month. Cancel anytime

Authors (2)

author image
Desislav Andreev

Desislav Andreev is a software engineer with a PhD in artificial intelligence systems and quantum machine learning. He has several publications in software engineering and AI applications. For his 10 years in the field he has a demonstrated history of working in automotive software engineering and in the area of the higher education. He is skilled in system and software architectures, operating systems, C and C++ development, autonomous driving and computer graphics. He is currently working as a Lead C++ Developer in VMware, developing its core software functionalities. He is also a lecturer at the Technical University of Sofia. He was previously a Technical Professional and software architect in the CRE and ADAS departments of Visteon Corporation, working closely with both OEMs and development teams.
Read more about Desislav Andreev

author image
Stanimir Lukanov

Stanimir Lukanov is a C++ expert, software tech lead and architect at VMWare. He has more than 15 years of professional experience in writing efficient and robust C++ enterprise code. Stanimir is a member of the Bulgarian National Body which is part of The C++ Standards Committee (JTC1/SC22/WG21). His interests are in the area of software security for distributed enterprise software systems. Since 2017 he has worked at VMWare where he currently leads a team which develops core security functionality in one of the major products in the company's portfolio. Before joining VMWare he held the position of senior software engineer at Visteon Corporation and Johnson Controls. He was responsible for defining software architecture, making code reviews, leading C++ training and delivering fast and robust C++ code for real-time automotive embedded systems.
Read more about Stanimir Lukanov