Semaphores 557
Semaphore Definition 558
A Theoretical Example 559
Linux Semaphore Facilities 560
semget 561
semop 561
semctl 562
Using Semaphores 563
Try It Out—Semaphores 563
Shared Memory 566
shmget 568
shmat 568
shmdt 569
shmctl 569
Try It Out—Shared Memory 570
Message Queues 573
msgget 574
msgsnd 574
msgrcv 575
msgctl 576
Try It Out—Message Queues 576
The CD Database Application 579
Try It Out—Revising the Server Functions 580
Try It Out—Revising the Client Functions 581
IPC Status Commands 583
Semaphores 583
Shared Memory 584
Message Queues 584
Summary 585
Chapter 15: Sockets 587
What Is a Socket? 588
Socket Connections 588
Try It Out—A Simple Local Client 588
Try It Out—A Simple Local Server 590
a544977 FM.qxd 12/1/03 8:55 AM Page xxi
Socket Attributes 592
Socket Domains 592
Socket Types 593
Socket Protocols 594
Creating a Socket 594
Socket Addresses 595
Naming a Socket 596
Creating a Socket Queue 596
Accepting Connections 597
Requesting Connections 597
Closing a Socket 598
Socket Communications 598
Try It Out—Network Client 599
Try It Out—Network Server 600
Host and Network Byte Ordering 601
Network Information 602
Try It Out—Network Information 604
Try It Out—Connecting to a Standard Service 606
The Internet Daemon (inetd) 608
Socket Options 609
Multiple Clients 610
Try It Out—A Server for Multiple Clients 610
select 613
Try It Out—select 614
Multiple Clients 616
Try It Out—An Improved Multiple Client/Server 616
Datagrams 619 Summary 622
Chapter 16: Programming GNOME Using GTK+ 623
Introducing X 623
X Server 624
X Client 624
X Protocol 624
Xlib 624
Toolkits 625
Window Managers 625
Other Ways to GUI—Platform-Independent Windowing APIs 625
Introducing GTK+ 626
GLib Type System 626
GTK+ Object System 627
xxiii
Contents
Introducing GNOME 628
Installing the GNOME/GTK+ Development Libraries 629
Try it Out—A Plain GtkWindow 631
Events, Signals, and Callbacks 632
Try It Out—A Callback Function 633
Packing Box Widgets 635
Try It Out—Widget Container Layout 636
GTK+ Widgets 638
GtkWindow 638
GtkEntry 639
Try It Out—Username and Password Entry 640
GtkSpinButton 643
Try It Out—GtkSpinButton 644
GtkButton 644
GtkToggleButton 645
GtkCheckButton 645
GtkRadioButton 645
Try It Out—GtkCheckButton, GtkToggleButton, and GtkRadioButton 646
GtkTreeView 648
Try It Out—GtkTreeView 650
GNOME Widgets 652
Try It Out—A GNOME Window 653
GNOME Menus 653
Try It Out—GNOME Menus 655
Try It Out—Menus with GNOME Macros 657
Dialogs 658
GtkDialog 658
Modal Dialog Box 660
Nonmodal Dialogs 661
GtkMessageDialog 662
CD Database Application 663
Try It Out—cdapp_gnome.h 664
Try It Out—interface.c 665
Try It Out—callbacks.c 669
Try It Out—main.c 673
Summary 675
Chapter 17: Programming KDE Using Qt 677
Introducing KDE and Qt 677
Installing Qt 678
Try It Out—QMainWindow 680
a544977 FM.qxd 12/1/03 8:55 AM Page xxiii
Signals and Slots 681
Try It Out—Signals and Slots 683
Try It Out—Using QBoxLayout Classes 686
Qt Widgets 688
QLineEdit 688
Try It Out—QLineEdit 689
Qt Buttons 691
QButton—The Button Base Class 691
QPushButton 692
QCheckBox 692
QRadioButton 693
Try It Out—QButtons 694
QComboBox 695
Try It Out—QComboBox 697
QListView 699
Try It Out—QListView 700
Dialogs 701
QDialog 702
Modal Dialogs 702
Nonmodal Dialogs 703
Semimodal Dialog 703
QMessageBox 704
QInputDialog 705
Using qmake to Simplify Writing Makefiles 707
Menus and Toolbars 708
Try It Out—A KDE Application with Menus and Toolbars 709
CD Database Application Using KDE/Qt 711
Try It Out—MainWindow 712
Try It Out—AddCdDialog 715
Try It Out—LogonDialog 717
Try It Out—main.cpp 719
Summary 720
Chapter 18: Device Drivers 721
Writing Device Drivers 721
Devices 722
Device Classes 723
User and Kernel Space 724
What Goes Where? 725
Building Modules 725
Data Types 727
Try It Out—A Kernel Module 727
xxv
Contents
Character Devices 729
File Operations 730
A Sample Driver: schar 732
The MSG Macro 733
Registering the Device 734
Module Usage Count 735
Open and Release 735
Reading the Device 736
The current Task 737
Wait Queues 738
Writing to the Device 739
Nonblocking Reads 740
Seeking 741
ioctl 741
Checking User Rights 744
poll 744
Try It Out—Reading and Writing to schar 745
Try It Out—ioctl 746
Module Parameters 747
Try It Out—modinfo 747
proc File System Interface 748
How schar Behaves 750
Time and Jiffies 750
Small Delays 752
Timers 752
Try It Out—The Timer Implementation in schar 754
Giving Up the Processor 755
Task Queues 756
The Predefined Task Queues 756
Memory Management 758
Virtual Memory Areas 759
Address Space 759
Types of Memory Locations 760
Getting Memory in Device Drivers 761
kmalloc 762
vmalloc 762
Transferring Data between User and Kernel Space 763
Moving More Data 764
Simple Memory Mapping 765
I/O Memory 766
Assignment of Devices in Iomap 768
I/O Memory mmap 768
Try It Out—The Iomap Module 769
a544977 FM.qxd 12/1/03 8:55 AM Page xxv
I/O Ports 771
Interrupt Handling 772
Allocating an Interrupt 773
Getting an Appropriate IRQ 774
The IRQ Handler 775
Bottom Halves 776
Re-entrancy 777
Disabling Single Interrupts 778
Atomicity 779
Protecting Critical Sections 780
Basic Spin Locks 780
Reader and Writer Locks 780
Automated Locking 781
Block Devices 781
radimo—A Simple RAM Disk Module 782
Size Issues 783
Registering a Block Device 784
Media Change 785
ioctl for Block Devices 785
The request Function 786
The Buffer Cache 788
Try It Out—radimo 789
Going Further 790
Debugging 790
Oops Tracing 790
Debugging Modules 792
The Magic Key 793
Kernel Debugger—kdb 793
Remote Debugging 794
General Notes on Debugging 794
Portability 795
Data Types 795
Endianess 795
Alignment 796
Anatomy of the Kernel Source 796 Summary 797
Chapter 19: Standards for Linux 799
The C Programming Language 800
A Brief History Lesson 800
The GNU Compiler Collection 801
xxvii
Contents
gcc Options 801
Compiler Options for Standards Tracking 802
Define Options for Standard Tracking 802
Compiler Options for Warnings 802
Interfaces and the LSB 803
LSB Standard Libraries 804
A Brief History Lesson 804
Using the LSB Standard for Libraries 805
LSB Users and Groups 805
LSB System Initialization 805
The Filesystem Hierarchy Standard 807
/bin 808
/boot 808
/dev 808
/etc 809
/home 809
/lib 809
/mnt 809
/opt 809
/root 809
/sbin 809
/tmp 809
/usr 810
/var 810
Further Reading about Standards 810 Summary 810
Index 811
a544977 FM.qxd 12/1/03 8:55 AM Page xxvii
Authors’ Acknowledgements
The authors would like to thank the many people who helped to make this book possible.
Neil would like to thank his wife, Christine, for her understanding; and his children, Alex and Adrian, for not complaining too loudly at Dad spending so long in The Den writing.
Rick would like to thank his wife, Ann, and our children, Jennifer and Andrew, for their very considerable patience during the evenings and weekends while Dad was yet again “doing book work.”
As for the publishing team, we’d both like to thank the folks at Wiley who helped us get this third edi- tion off the ground, especially Debra Williams Cauley for acquiring and administering all the talented individuals who worked on this book; James H. Russell for ensuring consistency, proper organization, presentation, and other duties; and Arthur Griffith and Tobias DiPasquale for their outstanding technical edits. Thanks also to Andrew Froggatt for his fantastic work on Chapters 16 and 17, to Clark Morgan and W. Kevin Pedigo for their input on Chapters 8 and 18, respectively, and to Pamela Hanley for her astute care in stewarding this book through Wiley’s production processes. We can say that this is a better book than it would have been without the efforts of all of you.
We would also like to thank our employers, Scientific Generics, Mobicom, and Celesio, for their support during the production of all three editions of this book.
Finally, we would like to pay homage to two important motivators who have helped make this book possible. Firstly, Richard Stallman for the excellent GNU tools and the idea of a free software environ- ment, which is now a reality with GNU/Linux, and secondly, Linus Torvalds for starting and continuing to inspire the co-operative development that gives us the ever-improving Linux kernel.
a544977 FM.qxd 12/1/03 8:55 AM Page xxix
Foreword by Alan Cox
Every computer programmer has his own piles of notes and scribbles. They have their code examples saved from the past heroic dive into the manuals or from Usenet, where sometimes even fools fear to fol- low. (The other body of opinion is that fools all get free Usenet access and use it nonstop.) It is therefore perhaps strange that so few books follow such a style. In the online world there are a lot of short, to-the- point documents about specific areas of programming and administration. The Linux documentation project released a whole pile of documents covering everything from installing Linux and Windows on the same machine to wiring your coffee machine to Linux. Seriously. Take a look at The Linux Documentation Project on http://www.tldp.org.
The book world, on the other hand, seems to consist mostly of either learned tomes, detailed and very complete works that you don’t have time to read, or books for complete beginners that you buy for friends as a joke. There are very few books that try to cover the basics of a lot of useful areas. This book is one of them, a compendium of those programmers’ notes and scribbles, deciphered (try reading a pro- grammer’s handwriting), edited, and brought together coherently as a book.
This updated third edition of Beginning Linux Programming has been reviewed and updated to reflect today’s Linux developments, including a chapter on programming with the Qt toolkit, the basis of the KDE GUI.
Chapter 18 is your chance to join the world of kernel programmers. As you will discover, it isn’t actually that different from writing modules for large application programs. Put on your pointy hat, grow a beard, drink Jolt Cola, and come join in the fun.
Alan a544977 FM.qxd 12/1/03 8:55 AM Page xxxi
Introduction
Welcome to Beginning Linux Programming, 3rd Edition, an easy-to-use guide to developing programs for the Linux and other UNIX-style operating systems.
In this book we aim to give you an introduction to a wide variety of topics important to you as a developer using Linux. The word beginning in the title refers more to the content than to your skill level. We’ve structured the book to help you learn more about what Linux has to offer, however much experience you have already. Linux programming is a large field and we aim to cover enough about a wide range of topics to give you a good “beginning” in each subject.
Who’s This Book For?
If you’re a programmer who wishes to get up to speed with the facilities that Linux (or UNIX) offers software developers, to maximize your programming time and your application’s use of the Linux system, you’ve picked up the right book. Clear explanations and a tried and tested step-by- step approach will help you progress rapidly and pick up all the key techniques.
We assume you have some experience in C and/or C++ programming, perhaps in Windows or some other system, but we try to keep the book’s examples simple so that you don’t need to be an expert C coder to follow this book. Where direct comparisons exist between Linux programming and C/C++ programming, these are indicated in the text.
As it aims to be a tutorial guide to the various tools and sets of functions/libraries available to you on most Linux systems as well as a handy reference you can return to, this book is unique in its straightforward approach, comprehensive coverage, and extensive examples.
Watch out if you’re totally new to Linux. This isn’t a book on installing or configur- ing Linux. If you want to learn more about administering a Linux system, you may wish to look at some complementary books such as Running Linux, 4th Edition, by Matt Welsh, Matthias Kalle Dalheimer, Terry Dawson, and Lar Kaufman (O’Reilly, ISBN 0596002726) or Linux System Administration: A User’s Guide, by Marcel Gagné (Addison-Wesley, ISBN 0201719347).
a544977 FM.qxd 12/1/03 8:55 AM Page xxxiii
What’s Covered in the Book
The book has a number of aims:
❑ To teach the use of the standard Linux C libraries and other facilities as specified by the various Linux and UNIX standards.
❑ To show how to make the most of the standard Linux development tools.
❑ To give a concise introduction to data storage under Linux using both the DBM and MySQL database systems.
❑ To show how to build graphical user interfaces for the X Window System. We will use both the GTK (the basis of the GNOME environment) and Qt (the basis of the KDE environment) libraries.
❑ Having given you firm grounding, we’ll progress to real-world applications that you want to program.
As we cover these topics, we introduce programming theory and then illustrate it with an appropriate example(s) and a clear explanation. In this way you can learn quickly on a first read and look back over things to brush up on all the essential elements if you need to.
While the small examples are designed mainly to illustrate a set of functions or some new theory in action, throughout the book lies a larger sample project: a simple database application for recording audio CD details. As your knowledge expands, you can develop, reimplement and extend the project to your heart’s content. That said, however, the CD application doesn’t dominate any chapter, so you can skip it if you want to, but we feel that it provides additional useful, in-depth examples of the techniques that we’ll discuss. It certainly provides an ideal way to illustrate each of the more advanced topics as they are introduced. Our first discussion of this application occurs at the end of Chapter 2 and shows how a fairly large shell script is organized, how the shell deals with user input, and how it can construct menus and store and search data.
After recapping the basic concepts of compiling programs, linking to libraries, and accessing the online manuals, you will take a sojourn into shells. You then get stuck into C programming, where we cover working with files, getting information from the Linux environment, dealing with terminal input and output, and the curseslibrary (which makes interactive input and output more tractable). You’re then ready to tackle reimplementing the CD application in C. The application design remains the same, but the code uses the curseslibrary for a screen-based user interface.
From there, we cover data management. Meeting the dbmdatabase library is sufficient cause for us to reimplement the application, but this time with a design that will re-emerge in some later chapters. In a later chapter we look at how the data could be stored in a relational database using MySQL, and we also reuse this data storage technique later in the chapter, so you can see how the techniques compare. The size of these recent applications means that we then need to deal with such nuts-and-bolts issues as debugging, source code control, software distribution, and makefiles.
You will also look at how different Linux processes can communicate, using a variety of techniques, and then look at how Linux programs can use sockets to support TCP/IP networking to different machines, including the issues of talking to machines that use different processor architectures.
xxxv
Introduction
Having got the foundations of Linux programming in place, we cover the creation of graphical programs.
We do this over two chapters, looking first at the GTK toolkit, which underlies the GNOME environment, and then at the Qt toolkit, which underlies the KDE environment.
As the book’s final “programming” chapter, we give an introduction to writing device drivers—an important step along the path to understanding the Linux kernel itself.
We finish off with a brief look at the standards that keep Linux systems from different vendors similar enough that we can move between them easily and write programs that will work on different distribu- tions of Linux.
As you’d expect, there’s a fair bit more in between, but we hope that this gives you a good idea of the material we’ll be discussing.
What You Need to Use This Book
In this book, we’ll give you a taste of programming for Linux. To help you get the most from the chap- ters, we would really like you to try out the examples as you read. These also provide a good base for experimentation and will hopefully inspire you to create programs of your own. We hope you will read this book in conjunction with experimenting on your own Linux installation.
Linux is available for many different systems. Its adaptability is such that enterprising souls have per- suaded it to run in one form or another on just about anything with a processor in it! Examples include systems based on the Alpha, SPARC, ARM, PowerPC, and 68000 CPUs as well as the Intel x86/Pentium- class processors (and compatibles) found in today’s PCs.
To develop this book we primarily used x86-based systems, but very little of what we cover is Intel-specific.
Although it is possible to run Linux on a 386 with 2-MB RAM and no hard disk (truly!), to run Linux suc- cessfully and follow the examples in this book, we recommend that you pick one of the more popular Linux distributions such as Red Hat, Debian, or SuSE, and check the hardware recommendations they give.
We wrote this book and developed the examples on two Linux systems with different specifications, so we’re confident that if you can run Linux, you can make good use of this book. Furthermore, we tested the code on other versions of Linux during the book’s technical review.
As for software requirements, we suggest that you use a recent version of a Linux distribution. Although it’s possible to put together a Linux from scratch, it’s much easier to start with a prepackaged version, and with many of the vendors now providing online updates to keep the versions of components updated, and bugs fixed, it’s a good way for most users to run their Linux systems.
Because Linux and the GNU toolset and others are released under the GPL, they have certain properties, one of which is freedom. They will always have the source code available, and no one can take that free- dom away. They are, therefore, examples of Open Source software—a weaker term for other software that may also have the source code available subject to certain conditions; see http://www.open source.org/for more details. With GNU/Linux, you will always have the option of support—either doing it yourself with the source code or hiring someone else. There are an ever-increasing number of companies offering commercial support for Linux and associated tools.
a544977 FM.qxd 12/1/03 8:55 AM Page xxxv
Source Code
We have tried to provide example programs and code snippets that best illustrate the concepts being dis- cussed in the text. Please note that, in order to make the new functionality being introduced as clear as possible, we have taken one or two liberties with coding style.
In particular, we do not always check that the return results from every function we call are what we expect. In production code for real applications we would certainly do this check, and you too should adopt a rigorous approach toward error handling. (We discuss some of the ways that errors can be caught and handled in Chapter 3.)
The complete source code from the book is available for download from http://www.wrox.com. The source code in the book is made available under the terms of the GNU General Public License, http://www.gnu.org/licenses/gpl.txt. The following permission statement applies to all the source code available in this book:
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Although all the code you need is listed in the book, we suggest you download a copy of the code to save yourself a lot of typing.
Conventions
To help you get the most from the text and keep track of what’s happening, we’ve used a number of con- ventions throughout the book:
When we introduce them, we highlight important words in italics. Characters we want you to type are in bold font. We show keyboard strokes like this: Ctrl+A.
Boxes like this one hold important, not-to-be-forgotten, mission-critical information that is directly relevant to the surrounding text.