Đăng ký Đăng nhập

Tài liệu Professional linux programming

.PDF
507
73
110

Mô tả:

www.it-ebooks.info 01_776130 ffirs.qxp 2/2/07 10:13 PM Page iii Professional Linux® Programming Jon Masters Richard Blum www.it-ebooks.info 01_776130 ffirs.qxp 2/2/07 10:13 PM Page ii www.it-ebooks.info 01_776130 ffirs.qxp 2/2/07 10:13 PM Page i Professional Linux® Programming www.it-ebooks.info 01_776130 ffirs.qxp 2/2/07 10:13 PM Page ii www.it-ebooks.info 01_776130 ffirs.qxp 2/2/07 10:13 PM Page iii Professional Linux® Programming Jon Masters Richard Blum www.it-ebooks.info 01_776130 ffirs.qxp 2/2/07 10:13 PM Page iv Professional Linux® Programming Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 Library of Congress Cataloging-in-Publication Data: Masters, Jon, 1981Professional Linux programming / Jon Masters, Richard Blum. p. cm. Includes index. ISBN: 978-0-471-77613-0 (paper/website) 1. Linux. 2. Operating systems (Computers) I. Blum, Richard, 1962- II. Title. QA76.76.O63M37153 2007 005.4’32—dc22 2006102202 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 Sections 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, 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-4355, or online at http://www.wiley.com/go/permissions. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks 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 registered 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. www.it-ebooks.info 01_776130 ffirs.qxp 2/2/07 10:13 PM Page v For Karin, whom I love very much.—Jon Masters To my wife Barbara.—Richard Blum www.it-ebooks.info 01_776130 ffirs.qxp 2/2/07 10:13 PM Page vi About the Authors Jon Masters is a 25-year-old British-born Linux kernel engineer, embedded systems specialist, and author who lives and works in the United States for Red Hat. Jon made UK history by becoming one of the youngest University students the country had ever seen, at the tender age of just 13. Having been through college twice by the time his peers were completing their first time around, and having been published over 100 times in a wide range of technical magazines, journals and books, Jon went on to work for a variety of multinational technology companies. He has worked extensively in the field of Embedded Systems, Enterprise Linux and Scientific instrumentation and has helped design anything and everything from Set Top Boxes to future NMR (MRI) imaging platforms. When not working on Enterprise Linux software for Red Hat, Jon likes to drink tea on Boston Common and read the collective works of Thomas Paine and other great American Revolutionaries of a bygone age. He dreams of a time when the world was driven not by electrons, but by wooden sailing ships and a universal struggle for the birth of modern nations. He plays the violin, and occasionally sings in choral ensembles, for which he has won several awards. For relaxation, Jon enjoys engaging in a little rock climbing. He lives in Cambridge, Massachusetts, just across the river Charles from historic Boston, and enjoys every minute of it. Jon has extensive experience in speaking about and training people to use a wide variety of Linux technologies and enjoys actively participating in many Linux User Groups the world over. Richard Blum has worked for over 18 years for a large U.S. government organization as a network and systems administrator. During this time he has had plenty of opportunities to work with Microsoft, Novell, and of course, UNIX and Linux servers. He has written applications and utilities using C, C++, Java, C#, Visual Basic, and shell script. Rich has a Bachelors of Science degree in Electrical Engineering, and a Masters of Science degree in Management, specializing in Management Information Systems, from Purdue University. He is the author of several books, including “sendmail for Linux” (2000, Sams publishing), “Running qmail” (2000, Sams publishing), “Postfix” (2001, Sams Publishing), “Open Source E-mail Security” (2001, Sams Publishing), “C# Network Programming” (2002, Sybex), “Network Performance Open Source Toolkit” (2003, John Wiley & Sons), and “Professional Assembly Language Programming” (2005, Wrox). When he is not being a computer nerd, Rich plays electric bass for the church worship and praise band, and enjoys spending time with his wife Barbara, and daughters Katie Jane and Jessica. www.it-ebooks.info 01_776130 ffirs.qxp 2/2/07 10:13 PM Page vii Credits Contributing Writers Graphics and Production Specialists Christopher Aillon Katherine and David Goodwin Matthew Walton Carrie A. Foster Jennifer Mayberry Barbara Moore Alicia B. South Acquisitions Editor Kit Kemper Quality Control Technicians Development Editor Cynthia Fields John Greenough Howard A. Jones Project Coordinator Adrienne Martinez Production Editor Eric Charbonneau Proofreading and Indexing Techbooks Copy Editor Foxxe Editorial Anniversary Logo Design Richard Pacifico Editorial Manager Mary Beth Wakefield Production Manager Tim Tate Vice President and Executive Group Publisher Richard Swadley Vice President and Executive Publisher Joseph B. Wikert www.it-ebooks.info 01_776130 ffirs.qxp 2/2/07 10:13 PM Page viii www.it-ebooks.info 01_776130 ffirs.qxp 2/2/07 10:13 PM Page ix Acknowledgments I sit here writing these acknowledgements on my 25th birthday, having spent many long evenings over the last year pouring over schedules, planning and even occasionally actually getting some writing done. When I first undertook to write this book, I could never have fully appreciated the amount of work it takes to put such a thing together nor the difficulties that would need to be overcome along the way. I started writing this book living just outside London and finished it less than a year later from my new home in Cambridge, Massachusetts, having decided to leave the country in the interim. Over the last year, a lot has changed for me both personally and professionally, but I am supported by a great network of friends and family who have helped make it possible. First and foremost I would like to thank the team I have worked with at Wiley — Debra, Adaobi, Kit, Howard and Carol as well as numerous others whose job it is to turn this manuscript into a finished book. Kit Kemper deserves special thanks for enduring my writing schedule and somehow making that just about work out in the end, as does Debra Williams-Cauley for believing that this project was a good idea in the first place. Howard Jones helped to keep me honest by doing an excellent job as my editor. This book would not exist without the inspiration I received from my good friends (and former bosses) Malcolm Buckingham and Jamie McKendry at Resonance Instruments (later Oxford Instruments), who used to moan about the lack of Linux-specific programming books. This book would also not exist without the kind contributions from several good friends of mine — Kat and David Goodwin, Matthew Walton, and Chris Aillon, thank you. Thanks also to Richard Blum for stepping up and joining the team once it became apparent to me that I couldn’t hope to finish this in time. You’ve all done a great job and I really do thank you very much. I have been helped along the way by my fantastic family — my parents Paula and Charles, my sisters Hannah Wrigley and Holly, my brother-in-law Joe, and occasional inspiration too from my grandmothers. I have also benefited from some of the best friends anyone could ask for — there are too many to list everyone individually, but I would like to specifically mention Hussein Jodiyawalla, Johannes Kling, Ben Swan, Paul Sladen, Markus Kobler, Tom Hawley, Sidarshan Guru Ratnavellu, Chris and Mad Ball (and Zoe, the cat), Emma Maule, John and Jan Buckman, Toby Jaffey and Sara, Sven Thorsten-Dietrich, Bill Weinberg, Daniel James, Joe Casad and Andrew Hutton and Emilie. Special thanks also to all of my friends at Red Hat, my boss and all the other hard-working people who help to make our company truly the greatest place to work anywhere in the world. Red Hat really understands what it means to work on Linux, and I am extremely grateful for having such a cool work environment, which really does encourage involvement in projects such as this one, in the true spirit of the Linux community — thanks, guys, you rock. Finally, I would like to thank Karin Worley for her friendship, which provided me with ample opportunity for procrastination during the final stages of this project. Karin, I’m not sure I would have completed it without the new-found sense of happiness that recently entered into my life. Jon Masters Cambridge, Massachusetts www.it-ebooks.info 01_776130 ffirs.qxp 2/2/07 10:13 PM Page x Acknowledgments Many thanks go to the great team of people at Wiley for their outstanding work on this project. Thanks to Kit Kemper, the Acquisitions Editor, for offering me the opportunity to work on this book. Also thanks to Howard Jones, the Developmental Editor, for keeping things on track and helping make this book presentable. I would also like to thank Carole McClendon at Waterside Productions, Inc. for arranging this opportunity for me, and for helping out in my writing career. Finally, I would like to thank my parents, Mike and Joyce Blum, for their dedication and support while raising me, and to my wife Barbara and daughters Katie Jane and Jessica for their love, patience, and understanding, especially while I’m writing. Richard Blum x www.it-ebooks.info 02_776130 ftoc.qxp 2/2/07 10:13 PM Page xi Contents Acknowledgments Introduction ix xix Chapter 1: Working with Linux A Brief History of Linux 1 2 The GNU Project The Linux Kernel Linux Distributions Free Software vs. Open Source Beginning Development 2 3 4 4 5 Choosing a Linux Distribution Installing a Linux Distribution Linux Community 6 8 15 Linux User Groups Mailing lists IRC Private Communities 15 16 16 16 Key Differences 16 Linux Is Modular Linux Is Portable Linux Is Generic 17 17 17 Summary 18 Chapter 2: Toolchains 19 The Linux Development Process Working with Sources Configuring to the Local Environment Building the Sources Components of the GNU Toolchain The GNU Compiler Collection 19 20 21 22 23 23 The GNU binutils GNU Make The GNU Debugger 34 39 40 www.it-ebooks.info 02_776130 ftoc.qxp 2/2/07 10:13 PM Page xii Contents The Linux Kernel and the GNU Toolchain Inline Assembly Attribute Tags Custom Linker Scripts 44 44 45 45 Cross-Compilation Building the GNU Toolchain Summary 46 47 48 Chapter 3: Portability 49 The Need for Portability The Portability of Linux 50 51 Layers of Abstraction Linux Distributions Building Packages Portable Source Code Internationalization 51 52 57 70 81 Hardware Portability 88 64-Bit Cleanliness Endian Neutrality Summary 89 89 92 Chapter 4: Software Configuration Management The Need for SCM Centralized vs. Decentralized Development Centralized Tools The Concurrent Version System Subversion 93 94 95 95 96 104 Decentralized tools 108 Bazaar-NG Linux kernel SCM (git) 109 112 Integrated SCM Tools 115 Eclipse 115 Summary 117 Chapter 5: Network Programming 119 Linux Socket Programming 119 Sockets Network Addresses Using Connection-Oriented Sockets Using Connectionless Sockets 120 122 123 130 xii www.it-ebooks.info 02_776130 ftoc.qxp 2/2/07 10:13 PM Page xiii Contents Moving Data 133 Datagrams vs. Streams Marking Message Boundaries Using Network Programming Libraries The libCurl Library Using the libCurl Library 133 137 140 140 141 Summary 147 Chapter 6: Databases 149 Persistent Data Storage 149 Using a Standard File Using a Database 150 150 The Berkeley DB Package 152 Downloading and Installing Building Programs Basic Data Handling 153 154 154 The PostgreSQL Database Server Downloading and Installing Building Programs Creating an Application Database Connecting to the Server Executing SQL Commands Using Parameters Summary 165 165 167 167 169 173 181 184 Chapter 7: Kernel Development 185 Starting Out 185 Kernel Concepts 199 A Word of Warning The Task Abstraction Virtual Memory Don’t Panic! 200 200 205 208 Kernel Hacking 208 Loadable Modules 209 Kernel Development Process Git: the “Stupid Content Tracker” The Linux Kernel Mailing List The “mm” Development Tree The Stable Kernel Team LWN: Linux Weekly News Summary 211 212 213 215 215 216 216 xiii www.it-ebooks.info 02_776130 ftoc.qxp 2/2/07 10:13 PM Page xiv Contents Chapter 8: Kernel Interfaces 217 What Is an Interface? 217 Undefined Interfaces 218 External Kernel Interfaces 219 System Calls The Device File Abstraction Kernel Events Ignoring Kernel Protections 219 224 238 239 Internal Kernel Interfaces 243 The Kernel API The kernel ABI 243 244 Summary 245 Chapter 9: Linux Kernel Modules 247 How Modules Work 247 Extending the Kernel Namespace No Guaranteed Module Compatibility 250 251 Finding Good Documentation 251 Linux Kernel Man Pages 251 Writing Linux Kernel Modules 252 Before You Begin Essential Module Requirements Logging Exported Symbols Allocating Memory Locking considerations Deferring work Further Reading 253 253 256 257 259 267 275 283 Distributing Linux Kernel Modules 284 Going Upstream Shipping Sources Shipping Prebuilt Modules 284 284 284 Summary 285 Chapter 10: Debugging 287 Debugging Overview 287 A Word about Memory Management 288 Essential Debugging Tools 289 The GNU Debugger Valgrind 289 298 xiv www.it-ebooks.info 02_776130 ftoc.qxp 2/2/07 10:13 PM Page xv Contents Graphical Debugging Tools 299 DDD Eclipse 299 302 Kernel Debugging 305 Don’t Panic! Making Sense of an oops Using UML for Debugging An Anecdotal Word A Note about In-Kernel Debuggers Summary 306 307 309 312 313 313 Chapter 11: The GNOME Developer Platform GNOME Libraries 315 316 Glib GObject Cairo GDK Pango GTK+ libglade GConf GStreamer 316 316 316 317 317 317 318 318 318 Building a Music Player 319 Requirements Getting Started: The Main Window Building the GUI Summary 319 319 321 340 Chapter 12: The FreeDesktop Project 341 D-BUS: The Desktop Bus 341 What Is D-Bus? Under D-Hood of D-Bus D-Bus Methods 342 342 346 Hardware Abstraction Layer 350 Making Hardware Just Work Hal Device Objects 350 353 The Network Manager Other Freedesktop Projects Summary 358 360 360 xv www.it-ebooks.info 02_776130 ftoc.qxp 2/2/07 10:13 PM Page xvi Contents Chapter 13: Graphics and Audio 361 Linux and Graphics 361 X Windows Open Graphics Library OpenGL Utilities Toolkit Simple Directmedia Layer 362 364 365 365 Writing OpenGL Applications 365 Downloading and Installing Programming Environment Using the GLUT Library 366 367 368 Writing SDL Applications 382 Downloading and Installing Programming Environment Using the SDL Library 382 383 383 Summary 394 Chapter 14: LAMP 395 What Is LAMP? 395 Apache MySQL PHP The Rebel Platform Evaluating the LAMP Platform 396 396 397 397 397 Apache 399 Virtual Hosting Installation and Configuration of PHP 5 Apache Basic Authentication Apache and SSL Integrating SSL with HTTP Authentication MySQL 400 401 402 402 403 404 Installing MySQL Configuring and Starting the Database Changing the Default Password The MySQL Client Interface Relational Databases SQL The Relational Model 404 404 405 405 405 406 409 PHP 411 The PHP Language Error Handling Error-Handling Exceptions 411 420 421 xvi www.it-ebooks.info 02_776130 ftoc.qxp 2/2/07 10:13 PM Page xvii Contents Optimization Techniques Installing Additional PHP Software Logging Parameter Handling Session Handling Unit Testing Databases and PHP PHP Frameworks The DVD Library Version Version Version Version 1: 2: 3: 4: 422 427 427 428 429 430 432 432 433 The Developer’s Nightmare Basic Application with DB-Specific Data Layer Rewriting the Data Layer, Adding Logging and Exceptions Applying a Templating Framework 433 434 437 441 Summary 442 Index GNU 443 473 xvii www.it-ebooks.info
- Xem thêm -

Tài liệu liên quan