Wrox Beginning Linux Programming 3rd Edition Jan 2004 ISBN 0764544977 pdf
Beginning Linux®Programming Third Edition
Neil Matthew Richard Stones
Beginning Linux®Programming Third Edition
Neil Matthew Richard Stones
® Beginning Linux Programming Third Edition
Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 Copyright © 2004 by Wiley Publishing, Inc. All rights reserved.
Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-mail: permcoordinator@wiley.com.
HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK, THEY MAKE NO REPRESENTA- TIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS.
THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR YOUR SIT- UATION. YOU SHOULD CONSULT WITH A PROFESSIONAL WHERE APPROPRIATE. NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CON- SEQUENTIAL, OR OTHER DAMAGES.
For general information on our other products and services please contact our Customer Care Depart- ment within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, Wrox, the Wrox logo, and related trade dress are trademarks or registered trade-
marks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. Linux is a trademark of Linus Torvalds. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Library of Congress Control Number: 2003115911
ISBN: 0-7645-4497-7 Printed in the United States of America 10 9 8 7 6 5 4 3 2 1
3B/RX/RS/QT/IN
About Neil Matthew
Neil Matthew has been interested in and has programmed computers since 1974. A mathematics graduate from the University of Nottingham, Neil is just plain keen on programming languages and likes to explore new ways of solving computing problems. He’s written systems to program in BCPL, FP (Functional Programming), Lisp, Prolog, and a structured BASIC. He even wrote a 6502 microprocessor emulator to run BBC microcomputer programs on UNIX systems.
In terms of UNIX experience, Neil has used almost every flavor since the late 1970s, including BSD UNIX, AT&T System V, Sun Solaris, IBM AIX, many others, and of course Linux. Neil can claim to have been using Linux since August 1993 when he acquired a floppy disk distribution of Soft Landing (SLS) from Canada, with kernel version 0.99.11. He’s used Linux-based computers for hacking C, C++, Icon, Prolog, Tcl, and Java at home and at work. Most of Neil’s “home” projects were originally developed using SCO UNIX, but they’ve all ported to Linux with little or no trouble. He says Linux is much easier because it supports quite a lot of features from other systems, so that both BSD- and System V–targeted programs will generally compile with little or no change. As the head of software and principal engineer at Camtec Electronics in the 1980s, Neil programmed in C and C++ for real-time embedded systems. Since then he’s worked on software development tech- niques and quality assurance. After a spell as a consultant with Scientific Generics he is currently work- ing as a systems architect with Celesio AG. Neil is married to Christine and has two children, Alexandra and Adrian. He lives in a converted barn in Northamptonshire, England. His interests include solving puzzles by computer, music, science fiction, squash, mountain biking, and not doing it yourself.
About Rick Stones
Rick started programming at school, more years ago than he cares to remember, on a 6502-powered BBC micro, which with the help of a few spare parts continued to function for the next 15 years. He graduated from Nottingham University with a degree in Electronic Engineering, but decided software was more fun. Over the years he has worked for a variety of companies, from the very small with just a dozen employ- ees, to the very large, including the IT services giant EDS. Along the way he has worked on a range of projects, from real-time communications to accounting systems, very large help desk systems, and more recently as the technical authority on a large EPoS and retail central systems program.
A bit of a programming linguist, he has programmed in various assemblers, a rather neat proprietary telecommunications language called SL-1, some FORTRAN, Pascal, Perl, SQL, and smidgeons of Python and C++, as well as C. (Under duress he even admits that he was once reasonably proficient in Visual Basic, but tries not to advertise this aberration.) Rick lives in a village in Leicestershire, England, with his wife Ann, children Jennifer and Andrew, and two cats. Outside work his main interest is classical music, especially early religious music, and he even does his best to find time for some piano practice. He is currently trying to learn to speak German.
Credits
Authors Neil Matthew Richard Stones Executive Editor Debra Williams Cauley Development Editor James H. Russell Production Editor Pamela Hanley Technical Editors Arthur Griffith Tobias DiPasquale Copy Editor Publication Services Senior Production Manager Fred Bernardi Editorial Manager Mary Beth Wakefield Vice President & Executive Group Publisher Richard Swadley
Vice President and Executive Publisher Bob Ipsen Vice President and Publisher Joseph B. Wikert Executive Editorial Director Mary Bednarek Project Coordinators Regina Snyder April Farling Graphics and Production Specialists Steved Arany Beth Brooks Carrie Foster Lauren Goddard Kristin McMullan Janet Seib Quality Control Technicians Laura Albert Andy Hollandbeck Rob Springer Proofreading and Indexing TECHBOOKS Production Services
Contents Foreword by Alan Cox xxxi Introduction xxxiii
9 Static Libraries
22 Pipes
21 Redirecting Input
21 Redirecting Output
19 Pipes and Redirection
18 What Is a Shell?
18 A Bit of Philosophy
17 Why Program with a Shell?
15 Chapter 2: Shell Programming
14 Summary
13 Try It Out—Manual Pages and info
12 Getting Help
10 Shared Libraries
10 Try It Out—Static Libraries
8 Library Files
1 An Introduction to UNIX, Linux, and GNU
8 Header Files
8 Applications
7 Development System Roadmap
6 Try It Out—Our First Linux C Program
5 The C Compiler
5 Linux Programs
4 Programming Linux
3 Linux Distributions
3 The GNU Project and the Free Software Foundation
2 What Is Linux?
2 UNIX Philosophy
1 A Brief History of UNIX
1 What Is UNIX?
23 Contents The Shell as a Programming Language
23 Interactive Programs
23 Creating a Script
25 Making a Script Executable
26 Shell Syntax
27 Variables
28 Quoting
28 Try It Out—Variables
29 Environment Variables
29 Parameter Variables
30 Try It Out—Parameter and Environment Variables
31 Conditions
32 The test, or [, Command
32 Control Structures
35
if
35 Try It Out—Using the if Command
35
elif
36 Try It Out—Doing Further Checks with an elif
36 A Problem with Variables
36 for
37 Try It Out—for Loop with Fixed Strings
38 Try It Out—for Loop with Wildcard Expansion
38
while
39 Try It Out—Here We Go Again, Again
40
until 41 case
41 Try It Out—Case I: User Input
42 Try It Out—Case II: Putting Patterns Together
42 Try It Out—Case IIl: Executing Multiple Statements
43 Lists
44 Try It Out—AND Lists
45 Try It Out—OR Lists
46 Statement Blocks
47 Functions
47 Try It Out—A Simple Function
47 Try It Out—Returning a Value
49 Commands
50
break
50 The : Command
51
viii
Contents
continue
51 The . Command
52 Try It Out—The Dot Command
53
echo 53 eval 54 exec 54 exit n 55 export
55 Try It Out—Exporting Variables
56
expr 56 printf 57 return 58 set 58 shift 59 trap
60 Try It Out—Trapping Signals
60
unset
62 Two More Useful Commands and Regular Expressions
62 Try It Out—find with Tests
64 Try It Out—Basic grep Usage
66 Try It Out—Regular Expressions
68 Command Execution
69 Arithmetic Expansion
70 Parameter Expansion
70 Try It Out—Parameter Processing
72 Here Documents
73 Try It Out—Using Here Documents
73 Try It Out—Another Use for a Here Document
74 Debugging Scripts
75 Going Graphical—The Dialog Utility
76 Try It Out—Using the dialog Utility
78 Try It Out
79 Putting It All Together
80 Requirements
81 Design
81 Try It Out—A CD Application
83 Notes on the Application
90 Summary
90 Contents
91 Linux File Structure
92 Directories
92 Files and Devices
93
/dev/console
93 /dev/tty
93 /dev/null
94 System Calls and Device Drivers
94 Library Functions
95 Low-Level File Access
96 write
96 read 97 open
98 Initial Permissions 100
umask 100 close 101 ioctl 102
Try It Out—A File Copy Program 102
Other System Calls for Managing Files 104
lseek 104 fstat, stat, and lstat 104 dup and dup2 106
The Standard I/O Library 107 fopen
108 fread 108 fwrite 109 fclose 109 fflush 109 fseek 110 fgetc, getc, and getchar 110 fputc, putc, and putchar 110 fgets and gets 111
Formatted Input and Output 111 printf, fprintf, and sprintf
112 scanf, fscanf, and sscanf 114 Other Stream Functions 116
Try It Out—Another File Copy Program 116
Stream Errors 117 Streams and File Descriptors 118
File and Directory Maintenance 118 chmod
118 chown 119 x
Contents unlink, link, and symlink
139 getopt_long
Host Information 158
Try It Out—User Information 156
User Information 155
Try It Out—tmpnam and tmpfile 154
Temporary Files 153
Try It Out—time 146 Try It Out—gmtime 148 Try It Out—ctime 150 Try It Out—strftime and strptime 152
Time and Date 146
Try It Out—environ 145
144 The environ Variable 145
143 Use of Environment Variables
142 Try It Out—getenv and putenv
140 Environment Variables
138 Try It Out—getopt
119 mkdir and rmdir 119 chdir and getcwd 120
137 getopt
135 Try It Out—Program Arguments
135 Program Arguments
Summary 134
Try It Out—Using mmap 132
130 mmap 131
The /proc File System 126 Advanced Topics: fcntl and mmap 130 fcntl
125 perror 126
125 strerror
Try It Out—A Directory-Scanning Program 122 Errors
121 readdir 121 telldir 122 seekdir 122 closedir 122
Scanning Directories 120 opendir
Try It Out—Host Information 159 xii Contents
Logging 160
Characters 185
Virtual Consoles 202 Pseudo Terminals 204
Try It Out—Your Very Own kbhit 200
Detecting Keystrokes 200
Try It Out—Total Terminal Control 198
Terminal Type 191 Identify Your Terminal Type 192 Using terminfo Capabilities 195
Terminal Output 191
Try It Out—A Password Program with termios 189 Try It Out—Reading Each Character 190
Terminal Speed 187 Additional Functions 188
Setting Terminal Modes from the Command Prompt 187
Accessing Terminal Modes from the Shell 186
The TIME and MIN Values 185
Input Modes 181 Output Modes 182 Control Modes 183 Local Modes 183 Special Control Characters 184
Try It Out—syslog 162 Try It Out—logmask 163
The termios Structure 180
Overview 178 Hardware Model 179
176 The Terminal Driver and the General Terminal Interface 178
176 Try It Out—Using /dev/tty
Try It Out—Checking for Output Redirection 175 Talking to the Terminal
Handling Redirected Output 174
Canonical versus Non-Canonical Modes 173
Try It Out—Menu Routines in C 172
171 Reading from and Writing to the Terminal 171
Summary 169
Try It Out—Resource Limits 167
Resources and Limits 164
Summary 204
Contents
226 Color
Simple Memory Allocation 250
Managing Memory 249
Chapter 7: Data Management 249
Summary 247
235 Try It Out—The Menu 236 Try It Out—Database File Manipulation 238 Try It Out—Querying the CD Database 243
233 Try It Out—A New CD Collection Application 233 Try It Out—Looking at main
231 The CD Collection Application
230 Try It Out—Using a Pad
230 Pads
229 Redefining Colors
227 Try It Out—-Colors
225 Try It Out—Using the Keypad
Chapter 6: Managing Text-Based Screens with curses 205
Compiling with curses 206 Concepts 207223 The Keypad
Subwindows 223 Try It Out—Subwindows
Optimizing Screen Refreshes 222
Try It Out—Multiple Windows 219
217 Generalized Functions 218 Moving and Updating a Window 218
Windows 217 The WINDOW Structure
Try It Out—Keyboard Modes and Input 216
215 Keyboard Input 215
214 Keyboard Modes
Try It Out—Moving, Inserting, and Attributes 212 The Keyboard
Initialization and Termination 210 Output to the Screen 210 Reading from the Screen 211 Clearing the Screen 211 Moving the Cursor 212 Character Attributes 212
Try It Out—A Simple curses Program 208
Try It Out—Simple Memory Allocation 250 Contents Allocating Lots of Memory
251 Try It Out—Asking for All Physical Memory 251 Try It Out—Available Memory
252 Abusing Memory
254 Try It Out—Abuse Your Memory
254 The Null Pointer
255 Try It Out—Accessing a Null Pointer
255 Freeing Memory
256 Try It Out—Freeing Memory
257 Other Memory Allocation Functions
257 File Locking
258 Creating Lock Files
258 Try It Out—Creating a Lock File
259 Try It Out—Cooperative Lock Files 260
Locking Regions 262
The F_GETLK Command 263
The F_SETLK Command 264
The F_SETLKW Command 264
Use of read and write with Locking 264
Try It Out—Locking a File with fcntl 265 Try It Out—Testing Locks on a File 267
Competing Locks 270
Try It Out—Competing Locks 270
Other Lock Commands 273 Deadlocks 273
Databases 274 The dbm Database
274
Introduction to dbm 274
Getting dbm 275
Troubleshooting and Reinstalling dbm 275
The dbm Routines 276 dbm Access Functions 277
dbm_open 277 dbm_store 277 dbm_fetch 277 dbm_close 278
Try It Out—A Simple dbm Database 278
Additional dbm Functions 280
dbm_delete 281 dbm_error 281
xiv
Contents
dbm_clearerr 281 dbm_firstkey and dbm_nextkey 281
Try It Out—Retrieving and Deleting 281
The CD Application 282
Updating the Design 283 The CD Database Application Using dbm 283
Try It Out—cd_data.h 284 Try It Out—app_ui.c 285 Try It Out—cd_access.c 295
Summary 302
303 Installation 304
Precompiled Packages 304 Post-Install Configuration 306 Post-Installation Troubleshooting 310
MySQL Administration 310
Commands 310
myisamchk 311 mysql 311 mysqladmin 312 mysqlbug 313 mysqlimport 314 mysqlshow 314
Creating Users and Giving Them Permissions 314
grant 314 revoke 316
Passwords 316 Creating a Database 317 Data Types 318
Boolean 318
Character 318
Number 318
Temporal 319
Creating a Table 319 Graphical Tools 322
Accessing MySQL Data from C 325
Connection Routines 326 Error Handling 330 xvi Contents
Executing SQL Statements 331
The Syntax of Makefiles 366 Options and Parameters to make 367
The rcs Command 380
RCS 380
Source Code Control 379
Try It Out—gcc -MM 379
Advanced Topic: Makefiles and Subdirectories 378 GNU make and gcc 378
Try It Out—Managing a Library 376
Built-in Rules 374 Suffix and Pattern Rules 375 Managing Libraries with make 376
Try It Out—Multiple Targets 372
Multiple Targets 372
Try It Out—A Makefile with Macros 370
Comments in a Makefile 370 Macros in a Makefile 370
Try It Out—A Simple Makefile 368
Rules 368
Dependencies 367
365 The make Command and Makefiles 366
SQL Statements That Return No Data 331
365 Problems of Multiple Source Files
Summary 363
Implementing the Interface 355
Test Application Interface 354
Interface Definition 353
Accessing the Application Data from C 353
Try It Out 352
Creating the Tables 348 Adding Some Data 350
The CD Database Application 347
Miscellaneous Functions 346
Processing Returned Data 340
Statements That Return Data 336
Try It Out 334 Try It Out 335
Discovering What You Inserted 334
The ci Command 381
Contents
Gathering the Software 401
Controlled Execution 424
Debugging without Recompiling 424
Try It Out—Debug Information 423
A Program with Bugs 418 Code Inspection 421 Instrumentation 422
417 General Debugging Techniques 418
417 Types of Errors
Summary 415
410 C-Forge 411 KDevelop 412 Other Environments 414
Other Package Formats 410 Development Environments 410 xwpe
Building an RPM Package with rpmbuild 407
Creating an RPM Spec File 403
The co Command 381
The rlog Command 382
RPM Packages 399
The patch Program 395 Other Distribution Utilities 397
Writing a Manual Page 391 Distributing Software 395
gCVS 390 BitKeeper 391
Accessing CVS over a Network 390
Using CVS Locally 387
SCCS 386 Comparing RCS and SCCS 386 CVS 386
Try It Out—ident 385
The ident Command 385
Try It Out—GNU make with RCS 385
Identifying Revisions 383
The rcsdiff Command 383
Working with RPM Package Files 400 Installing RPM Packages 400 Building RPM Packages 401 xviii Contents
Debugging with gdb 425
445 Process Structure 446
Zombie Processes 460
Try It Out—wait 458
Waiting for a Process 458
Try It Out—fork 457
Duplicating a Process Image 455
Try It Out—execlp 454
Replacing a Process Image 453
Try It Out—system 452
Starting New Processes 451
The Process Table 447 Viewing Processes 447 System Processes 449 Process Scheduling 450
445 What Is a Process?
Starting gdb 425 Running a Program 426 Stack Trace 427 Examining Variables 427 Listing the Program 428 Setting Breakpoints 429 Patching with the Debugger 432 Learning More about gdb 433
442 Summary 444
442 Try It Out—valgrind
441 valgrind
441 Try It Out—ElectricFence
440 ElectricFence
439 Memory Debugging
Assertions 439 Try It Out—assert
Execution Profiling with prof/gprof 438
ctags 436 cxref 436 cflow 437
Lint: Removing the Fluff from Your Programs 434 Function Call Tools 436
More Debugging Tools 434
Try It Out—Zombies 460
Contents Input and Output Redirection
462 Try It Out—Redirection
462 Threads
463 Signals
463 Try It Out—Signal Handling
465 Sending Signals
467 Try It Out—An Alarm Clock
468
A Robust Signals Interface 470
Try It Out—sigaction 470
Signal Sets 471
sigaction Flags 473
Common Signal Reference 474
Summary 476
Chapter 12: POSIX Threads 477
What Is a Thread? 477
Advantages and Drawbacks of Threads 478
A First Threads Program 479
Try It Out—A Simple Threaded Program 481
Simultaneous Execution 483
Try It Out—Simultaneous Execution of Two Threads 483 Synchronization 485
Synchronization with Semaphores 485
Try It Out—A Thread Semaphore 486
Synchronization with Mutexes 490
Try It Out—A Thread Mutex 490
Thread Attributes 494
Try It Out—Setting the Detached State Attribute 495
Thread Attributes—Scheduling 497
Try It Out—Scheduling 497
Canceling a Thread 498
Try It Out—Canceling a Thread 499
Threads in Abundance 501
Try It Out—Many Threads 501
Summary 504
Chapter 13: Inter-Process Communication: Pipes 505
What Is a Pipe? 505 Process Pipes 506popen 506 pclose 507
Try It Out—Reading Output from an External Program 507 Contents Sending Output to popen
508 Try It Out—Sending Output to an External Program 508
Passing More Data 509
Try It Out—Reading Larger Amounts of Data from a Pipe 509 How popen Is Implemented
510 Try It Out—popen Starts a Shell
510 The Pipe Call
511 Try It Out—The pipe Function
512 Try It Out—Pipes across a fork 513
Parent and Child Processes 514
Try It Out—Pipes and exec 515
Reading Closed Pipes 516 Pipes Used as Standard Input and Output 517
File Descriptor Manipulation by close and dup 517
Try It Out—Pipes and dup 518
Named Pipes: FIFOs 520
Try It Out—Creating a Named Pipe 521
Accessing a FIFO 522
Try It Out—Accessing a FIFO File 522
Opening a FIFO with open 523
Try It Out—Opening FIFO Files 524
O_RDONLY and O_WRONLY with No O_NONBLOCK 525 O_RDONLY with O_NONBLOCK and O_WRONLY 526 Reading and Writing FIFOs
526
Try It Out—Inter-Process Communication with FIFOs 527 Advanced Topic: Client/Server Using FIFOs 529
Try It Out—An Example Client/Server Application 530 The CD Database Application
533 Aims
534 Implementation 534 Try It Out—The Header File, cliserv.h
536 Client Interface Functions
538 Try It Out—The Client’s Interpreter
538
Searching the Database 542
Try It Out—Searching 543
The Server Interface 544
Try It Out—server.c 544
The Pipe 548
Try It Out—Pipes Implementation Header 549
Server-Side Functions 549
Try It Out—Server Functions 549 Try It Out—Plumbing the Pipes 551 xx
Contents
Message Queues 573 msgget
What Is a Socket? 588 Socket Connections 588
Chapter 15: Sockets 587
Summary 585
Semaphores 583 Shared Memory 584 Message Queues 584
IPC Status Commands 583
Try It Out—Revising the Server Functions 580 Try It Out—Revising the Client Functions 581
The CD Database Application 579
Try It Out—Message Queues 576
574 msgsnd 574 msgrcv 575 msgctl 576
Try It Out—Shared Memory 570
Client-Side Functions 552
568 shmat 568 shmdt 569 shmctl 569
Shared Memory 566 shmget
Try It Out—Semaphores 563
Using Semaphores 563
semget 561 semop 561 semctl 562
Chapter 14: Semaphores, Shared Memory, and Message Queues 557
Semaphores 557 Semaphore Definition 558 A Theoretical Example 559 Linux Semaphore Facilities 560Summary 555
Application Summary 554
Try It Out—Client Functions 552 Try It Out—Getting Server Results 553
Try It Out—A Simple Local Client 588 Try It Out—A Simple Local Server 590 xxii Contents
Socket Attributes 592
613 Try It Out—select
Introducing GTK+ 626
X Protocol 624 Xlib 624 Toolkits 625 Window Managers 625 Other Ways to GUI—Platform-Independent Windowing APIs 625
X Client 624
X Server 624
623
Datagrams 619 Summary 622
616 Try It Out—An Improved Multiple Client/Server 616
614 Multiple Clients
Try It Out—A Server for Multiple Clients 610 select
Socket Domains 592
Multiple Clients 610
The Internet Daemon (inetd) 608 Socket Options 609
Try It Out—Network Information 604 Try It Out—Connecting to a Standard Service 606
Network Information 602
Host and Network Byte Ordering 601
Try It Out—Network Client 599 Try It Out—Network Server 600
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
Socket Protocols 594
Socket Types 593
GLib Type System 626 GTK+ Object System 627
Contents Introducing GNOME
Try It Out—GtkCheckButton, GtkToggleButton, and GtkRadioButton 646 GtkTreeView
677 Installing Qt 678
Summary 675
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
CD Database Application 663
GtkDialog 658 Modal Dialog Box 660 Nonmodal Dialogs 661 GtkMessageDialog 662
Dialogs 658
655 Try It Out—Menus with GNOME Macros 657
653 Try It Out—GNOME Menus
653 GNOME Menus
652 Try It Out—A GNOME Window
650 GNOME Widgets
648 Try It Out—GtkTreeView
GtkRadioButton 645
628 Installing the GNOME/GTK+ Development Libraries 629 Try it Out—A Plain GtkWindow
GtkCheckButton 645
GtkToggleButton 645
644
644 GtkButton
643 Try It Out—GtkSpinButton
Try It Out—Username and Password Entry 640 GtkSpinButton
638 GtkEntry 639
638 GtkWindow
636 GTK+ Widgets
635 Try It Out—Widget Container Layout
633 Packing Box Widgets
632 Try It Out—A Callback Function
631 Events, Signals, and Callbacks
Try It Out—QMainWindow 680 Contents 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
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 xxiv
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 xxvi Contents
I/O Ports 771
Media Change 785 ioctl for Block Devices 785 The request Function 786 The Buffer Cache 788
800 The GNU Compiler Collection 801
800 A Brief History Lesson
799 The C Programming Language
Anatomy of the Kernel Source 796 Summary 797
795 Endianess 795 Alignment 796
Portability 795 Data Types
Oops Tracing 790 Debugging Modules 792 The Magic Key 793 Kernel Debugger—kdb 793 Remote Debugging 794 General Notes on Debugging 794
Going Further 790
Try It Out—radimo 789
Registering a Block Device 784
Interrupt Handling 772
Size Issues 783
782
Block Devices 781 radimo—A Simple RAM Disk Module
Automated Locking 781
Reader and Writer Locks 780
Basic Spin Locks 780
The IRQ Handler 775 Bottom Halves 776 Re-entrancy 777 Disabling Single Interrupts 778 Atomicity 779 Protecting Critical Sections 780
Getting an Appropriate IRQ 774
Allocating an Interrupt 773
Debugging 790
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
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.
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
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.
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).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. Introduction
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.