+ All Categories
Home > Documents > Versão traduzida de book

Versão traduzida de book

Date post: 10-Nov-2014
Category:
Upload: karla-costa
View: 129 times
Download: 21 times
Share this document with a friend

If you can't read please download the document

Transcript

Verso traduzida de book.pdf Handbook FreeBSD Developers ' *Page 1* *Page 1* *FreeBSD Developers' Handbook* *Handbook FreeBSD Developers '* *The FreeBSD Documentation Project* *O Projeto de Documentao do FreeBSD* -----------------------------------------------------------------------*Page 2* *Page 2* *FreeBSD Developers' Handbook* *Handbook FreeBSD Developers '* by The FreeBSD Documentation Project pelo Projeto de Documentao do FreeBSD Published August 2000 Publicada agosto 2000 Copyright 2000, 2001 by The FreeBSD Documentation Project Copyright 2000, 2001 por O Projeto de Documentao do FreeBSD Welcome to the Developers' Handbook. Bem-vindo ao Manual dos Desenvolvedores. This manual is a /work in progress/ and is the work of many individuals. Este manual um /trabalho em andamento/ e o trabalho de muitos indivduos. Many sections do not yet exist and some of those that do exist need to be updated. Muitas sees ainda no existem e algumas das que existem precisam ser atualizadas. If you are interested in helping Se voc estiver interessado em ajudar with this project, send email to the FreeBSD documentation project mailing list < com este projeto, envie um email para o FreeBSD documentao do projeto lista de discusso < [email protected] [email protected] >. >. The latest version of this document is always available from the FreeBSD World Wide Web server A verso mais recente deste documento est sempre disponvel a partir do servidor Web FreeBSD World Wide (http://www.FreeBSD.org/). (Http://www.FreeBSD.org/). It may also be downloaded in a variety of formats and compression options from the Tambm pode ser baixado em uma variedade de formatos e opes de compresso a partir da FreeBSD FTP server (ftp://ftp.FreeBSD.org/pub/FreeBSD/doc) or one of the numerous mirror sites FreeBSD servidor FTP (ftp://ftp.FreeBSD.org/pub/FreeBSD/doc) ou um dos numerosos sites espelhos (http://www.freebsd.org/handbook/mirrors-ftp.html). (Http://www.freebsd.org/handbook/mirrors-ftp.html). Redistribution and use in source (SGML DocBook) and 'compiled' forms (SGML, HTML, PDF, PostScript, RTF and so forth) with or without A redistribuio e utilizao do cdigo fonte (SGML DocBook) ou formato 'compilado' (SGML, HTML, PDF, PostScript, RTF e assim por diante) com ou sem modification, are permitted provided that the following conditions are met: modificao, so permitidas desde que as seguintes condies sejam atendidas: 1. 1. Redistributions of source code (SGML DocBook) must retain the above copyright notice, this list of conditions As redistribuies do cdigo fonte (SGML DocBook) devem reter o aviso de copyright acima, esta lista de condies and the following disclaimer as the first lines of this file unmodified. eo aviso a seguir nas primeiras linhas deste arquivo no modificadas. 2. 2. Redistributions in compiled form (transformed to other DTDs, converted to PDF, PostScript, RTF and other As redistribuies em forma compilada (transformada para outros DTDs, convertida para PDF, PostScript, RTF e outros

formats) must reproduce the above copyright notice, this list of conditions and the following disclaimer in the formatos) devem reproduzir o aviso de copyright acima, esta lista de condies ea seguinte iseno de responsabilidade na documentation and/or other materials provided with the distribution. documentao e / ou outros materiais fornecidos com a distribuio. *Important:* THIS DOCUMENTATION IS PROVIDED BY THE FREEBSD DOCUMENTATION PROJECT "AS IS" *Importante:* O DOCUMENTAO OFERECIDO PELO PROJETO DE DOCUMENTAO DO FREEBSD "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED E QUALQUER GARANTIA EXPRESSA OU implcita, incluindo, mas no limitado a, GARANTIAS WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. GARANTIAS DE COMERCIALIZAO E ADEQUAO A UM PROPSITO ESPECFICO. IN IN NO EVENT SHALL THE FREEBSD DOCUMENTATION PROJECT BE LIABLE FOR ANY DIRECT, INDIRECT, NO CASO DO PROJETO DE DOCUMENTAO DO FREEBSD SER RESPONSVEL POR QUAISQUER DANOS DIRETOS, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED , ESPECIAIS, EXEMPLARES OU EMERGENTES incidental (INCLUINDO, SEM LIMITAO TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR AQUISIO DE BENS OU SERVIOS, PERDA DE USO, DADOS OU LUCROS OU BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN INTERRUPO DE NEGCIOS) CAUSADOS E EM QUALQUER TEORIA DE RESPONSABILIDADE, SEJA EM CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY CONTRATO, RESPONSABILIDADE OBJETIVA OU DELITO (INCLUINDO NEGLIGNCIA OU NO) DECORRENTE DE QUALQUER WAY OUT OF THE USE OF THIS DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH FORMA DE USO DA DOCUMENTAO, MESMO QUE AVISADO DA POSSIBILIDADE DE TAIS DAMAGE. DANO. -----------------------------------------------------------------------*Page 3* *Pgina 3* *Table of Contents* *ndice analtico* *I. Introduction* *I. Introduo* 1. 1. Developing on Desenvolvendo em 2. 2. The BSD Vision A viso BSD 3. 3. Architectural Overview Viso geral da arquitetura 4. 4. The Layout of /usr/src O layout do arquivo / usr / src *II.* *II.* 5. 5. Programming Programao 5.1. 5.1. 5.2. 5.2. 5.3. 5.3. Introduction to Programming Introduo Programao 5.4. 5.4. Compiling with Compilando com cc cc 5.5. 5.5. Make Fazer 5.6. 5.6. 5.7. 5.7. Using Emacs as a Development Environment................. ...................................................................25 Usando Emacs como um ambiente de desenvolvimento ................. ........................... ........................................ 25

5.8. 5.8. Further Reading Leitura 6. 6. Secure Proteger 6.1. 6.1. 6.2. 6.2. Secure Design Projeto seguro 6.3. 6.3. Buffer Overflows Buffer overflows 6.4. 6.4. SetUID SetUID 6.5. 6.5. Limiting your program's Limitar o seu programa de 6.6. 6.6. 6.7. 6.7. Race Corrida *III.* *III.* *Kernel* *Ncleo* 7. 7. History of the Unix Histria do Unix 8. 8. Locking Notes Bloqueio Notas 8.1. 8.1. 8.2. 8.2. Lock Manager Lock Manager 8.3. 8.3. Atomically Protected Variables Variveis atomicamente Protegidas *IV.* *IV.* *Memory* *Memria* 9. 9. Virtual Memory System Sistema de Memria Virtual 9.1. 9.1. The FreeBSD VM O FreeBSD VM 10. 10. 10.1. 10.1. DMA: What it is and How it Works ............... ................................................................................ ..55 DMA: O que e como funciona ............... .......................... .................................................. ...... 55 *V. I/O* *V. I / O* 11. 11. /3/ /3/ -----------------------------------------------------------------------*Page 4* *Page 4* *VI.* *VI.* *Interprocess Communication* *Comunicao entre* 12. 12. *VII.* *VII.* *Networking* *Networking* 13. 13. Sockets Sockets 14. 14. IPv6 Internals Internals IPv6 14.1. 14.1. IPv6/IPsec IPv6/IPsec *VIII.* *VIII.* *Network* *Rede* 15. 15. *IX.* *IX.* *Terminal Handling* *Terminal Handling* 16. 16. *X.* *X.* 17. 17. *XI.* *XI.* *Device* *Dispositivo* 18. 18. Writing FreeBSD Device Escrevendo dispositivo FreeBSD 18.1. 18.1. 18.2. 18.2. Dynamic Kernel Linker Facility KLD................ ..........................................................................102 Dinmica Kernel Linker Facility - KLD ................ ............................ .............................................. 102 18.3. 18.3. Accessing a device driver Acessando um

driver de dispositivo 18.4. 18.4. Character Carter 18.5. 18.5. Network Rede 19. 19. ISA device drivers Drivers de dispositivos ISA 19.1. 19.1. 19.2. 19.2. Basic Bsico 19.3. 19.3. Device_t Device_t 19.4. 19,4. Config file and the order of identifying and probing during auto-configuration........ ....................113 Arquivo de configurao ea ordem de identificar e investigar durante a configurao automtica ........ .................... 113 19.5. 19.5. 19.6. 19.6. Bus memory Memria Bus 19.7. 19.7. 19.8. 19.8. 19.9. 19.9. xxx_isa_attach xxx_isa_attach 19.10. 19.10. xxx_isa_detach xxx_isa_detach 19.11. 19.11. xxx_isa_shutdown xxx_isa_shutdown 20. 20. PCI PCI 20.1. 20.1. Probe and Sonda e 20.2. 20,2. Bus nibus 21. 21. Common Access Method SCSI Common Access Method SCSI 21.1. 21.1. 21.2. 21.2. General Geral 21.3. 21.3. /4/ /4/ -----------------------------------------------------------------------*Page 5* *Page 5* 21.4. 21.4. Asynchronous Events Eventos assncronos 21.5. 21.5. 21.6. 21,6. Errors Erros 21.7. 21,7. Timeout Timeout 22. 22. USB Devices Dispositivos USB 22.1. 22.1. 22.2. 22.2. Host Hospedeiro 22.3. 22.3. USB Device Information Informaes sobre o dispositivo USB 22.4. 22,4. Device probe and Sonda dispositivo e 22.5. 22.5. USB Drivers Protocol USB Drivers Protocolo 23. 23. NewBus NewBus *XII.* *XII.* *Architectures* *Arquiteturas* 24. 24. x86 Assembly Language x86 Linguagem Assembly 24.1. 24.1. 24.2. 24.2. The Tools As ferramentas 24.3. 24.3. System Calls Chamadas do sistema 24.4. 24,4. Return Voltar 24.5. 24.5. Creating Portable Criao Porttil 24.6. 24,6. Our First Nosso primeiro 24.7. 24,7. Writing Unix Escrevendo Unix 24.8. 24,8. Buffered Input and Entrada e tamponado 24.9. 24.9. Command-line De linha de comando 24.10. 24.10. Unix Unix

24.11. 24.11. Working with Trabalhando com 24.12. 24.12. 24.13. 24,13. 25. 25. 26. 26. IA-64 IA-64 *XIII.* *XIII.* 27. 27. Truss Trelia *XIV.* *XIV.* *Compatibility* *Compatibilidade* 28. 28. Linux Linux *XV.* *XV.* /5/ /5/ -----------------------------------------------------------------------*Page 6* *Page 6* *List of Tables* *Lista de Tabelas* 8-1. 8-1. Mutex Mutex 8-2. 8-2. lockmgr(9) Lock lockmgr (9) Trava *List of Examples* *Lista de Exemplos* 5-1. 5-1. A sample Uma amostra .emacs . Emacs /1/ /1/ -----------------------------------------------------------------------*Page 7* *Pgina 7* *I. Introduction* *I. Introduo* -----------------------------------------------------------------------*Page 8* *Page 8* *Chapter 1.* *Captulo 1.* *Developing on FreeBSD* *Desenvolver no FreeBSD* This will need to discuss FreeBSD as a development platform, the vision of BSD, architectural overview, layout of Isto ter de discutir FreeBSD como uma plataforma de desenvolvimento, a viso do BSD, viso geral da arquitetura, layout /usr/src, history, etc. / Usr / src, histria, etc Thank you for considering FreeBSD as your development platform! Obrigado por considerar FreeBSD como sua plataforma de desenvolvimento! We hope it will not let you down. Esperamos que ele no vai deixar voc para baixo. /1/ /1/ -----------------------------------------------------------------------*Page 9* *Page 9* *Chapter 2.* *Captulo 2.* *The BSD Vision* *A viso BSD* /1/ /1/ -----------------------------------------------------------------------*Page 10* *Page 10* *Chapter 3.* *Captulo 3.* *Architectural Overview* *Viso geral da arquitetura* /2/ /2/ -----------------------------------------------------------------------*Page 11* *Page 11* *Chapter 4.* *Captulo 4.* *The Layout of /usr/src* *O layout do arquivo / usr / src* The complete source code to FreeBSD is available from our public CVS repository. O cdigo-fonte completo para o FreeBSD est disponvel no nosso repositrio CVS pblico. The source code is normally O cdigo-fonte normalmente installed in instalado /usr/src / Usr / src

which contains the following subdirectories. que contm os seguintes subdirectrios. *Directory* *Diretrio* *Description* *Descrio* bin/ bin / Source for files in Fonte para arquivos em /bin / Bin contrib/ contrib / Source for files from contributed software. Fonte para arquivos de software contribudo. crypto/ crypto / DES source DES fonte etc/ etc / Source for files in Fonte para arquivos em /etc / Etc games/ jogos / Source for files in Fonte para arquivos em /usr/games / Usr / games gnu/ gnu / Utilities covered by the GNU Public License Utilities abrangidos pela Licena Pblica GNU include/ include / Source for files in Fonte para arquivos em /usr/include / Usr / include kerberosIV/ kerberosIV / Source for Kerbereros version IV Fonte para Kerbereros verso IV kerberos5/ Kerberos5 / Source for Kerbereros version 5 Fonte para Kerbereros verso 5 lib/ lib / Source for files in Fonte para arquivos em /usr/lib / Usr / lib libexec/ libexec / Source for files in Fonte para arquivos em /usr/libexec / Usr / libexec release/ release / Files required to produce a FreeBSD release Arquivos necessrios para produzir uma verso do FreeBSD sbin/ sbin / Source for files in Fonte para arquivos em /sbin / Sbin secure/ garantir / FreeSec sources Fontes FreeSec share/ share / Source for files in Fonte para arquivos em /sbin / Sbin sys/ sys / Kernel source files Arquivos-fonte do kernel tools/ ferramentas / Tools used for maintenance and testing of FreeBSD Ferramentas utilizadas para manuteno e testes de FreeBSD usr.bin/ usr.bin / Source for files in Fonte para arquivos em /usr/bin / Usr / bin usr.sbin/ usr.sbin / Source for files in Fonte para arquivos em /usr/sbin / Usr / sbin /3/ /3/ -----------------------------------------------------------------------*Page 12* *Page 12*

*II.* *II.* *Basics* *Basics* -----------------------------------------------------------------------*Page 13* *Page 13* *Chapter 5.* *Captulo 5.* *Programming Tools* *Ferramentas de Programao* /This chapter was written by James Raynard ./ /Modifications for the Developers'/ /Modificaes para os desenvolvedores "/ /Handbook by Murray Stokely ./ *5.1.* *5.1.* *Synopsis* *Sinopse* This document is an introduction to using some of the programming tools supplied with FreeBSD, although much of Este documento uma introduo ao uso de alguma das ferramentas de programao fornecidas com o FreeBSD, embora grande parte it will be applicable to many other versions of Unix. ela ser aplicvel a muitas outras verses do Unix. It does /not/ attempt to describe coding in any detail. Ele /no/ tenta descrever a codificao em nenhum detalhe. Most of the A maior parte do document assumes little or no previous programming knowledge, although it is hoped that most programmers will documento pressupe o conhecimento de programao anterior pouca ou nenhuma, embora espera-se que a maioria dos programadores find something of value in it encontrar algo de valor nele *5.2.* *5.2.* *Introduction* *Introduo* FreeBSD offers an excellent development environment. FreeBSD oferece um ambiente de desenvolvimento excelente. Compilers for C, C++, and Fortran and an assembler come Compiladores para C, C + + e Fortran e um montador vir with the basic system, not to mention a Perl interpreter and classic Unix tools such as com o sistema bsico, para no mencionar um interpretador Perl e ferramentas Unix clssicos como sed sed and e awk awk . . If that is not Se no for esse enough, there are many more compilers and interpreters in the Ports collection. suficiente, h muitas mais compiladores e intrpretes da coleo Portas. FreeBSD is very compatible with FreeBSD muito compatvel com standards such as POSIX and ANSI C, as well with its own BSD heritage, so it is possible to write applications that padres como POSIX e ANSI C, bem com a sua prpria herana BSD, por isso possvel escrever aplicaes que will compile and run with little or no modification on a wide range of platforms. ir compilar e executar com pouca ou nenhuma modificao em uma ampla gama de plataformas. However, all this power can be rather overwhelming at first if you've never written programs on a Unix platform No entanto, todo este poder pode ser um pouco esmagadora na primeira, se voc nunca programas escritos em uma plataforma Unix before. antes. This document aims to help you get up and running, without getting too deeply into more advanced topics. Este documento tem como objetivo ajud-lo a se levantar e correr, sem entrar muito profundamente em tpicos mais avanados. The intention is that this document should give you enough of the basics to be able to make some sense of the A inteno que este documento

deve dar-lhe o suficiente dos princpios bsicos para ser capaz de fazer algum sentido da documentation. documentao. Most of the document requires little or no knowledge of programming, although it does assume a basic competence A maior parte do documento requer pouco ou nenhum conhecimento de programao, embora isto assume uma competncia bsica with using Unix and a willingness to learn! com o uso de Unix e uma vontade de aprender! *5.3.* *5.3.* *Introduction to Programming* *Introduo Programao* A program is a set of instructions that tell the computer to do various things; sometimes the instruction it has to Um programa um conjunto de instrues que dizem ao computador para fazer vrias coisas, s vezes a instruo que tem para perform depends on what happened when it performed a previous instruction. realizar depende do que aconteceu quando ele executou uma instruo anterior. This section gives an overview of the Esta seo apresenta uma viso geral do two main ways in which you can give these instructions, or commands as they are usually called. duas principais maneiras em que voc pode dar estas instrues, ou "comandos", como so normalmente chamados. One way uses an Um modo usa uma /interpreter/ , the other a /compiler/ . /intrprete,/ o outro um /compilador./ As human languages are too difficult for a computer to understand in an Como as lnguas humanas so muito difceis para um computador para entender em um unambiguous way, commands are usually written in one or other languages specially designed for the purpose. forma inequvoca, os comandos so geralmente escritos em um ou outros idiomas, especialmente concebidos para o efeito. /5/ /5/ -----------------------------------------------------------------------*Page 14* *Page 14* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ *5.3.1.* *5.3.1.* *Interpreters* *Intrpretes* With an interpreter, the language comes as an environment, where you type in commands at a prompt and the Com um intrprete, a linguagem surge como um ambiente, onde voc digita comandos em um prompt eo environment executes them for you. ambiente executa-los para voc. For more complicated programs, you can type the commands into a file and get Para programas mais complicados, voc pode digitar os comandos em um arquivo e obter the interpreter to load the file and execute the commands in it. o intrprete para carregar o arquivo e execute os comandos nele. If anything goes wrong, many interpreters will drop Se algo der errado, muitos intrpretes vai cair you into a debugger to help you track down the problem. lo em um depurador para ajud-lo a rastrear o problema. The advantage of this is that you can see the results of your commands immediately, and mistakes can be corrected A vantagem disto que voc pode ver os resultados de seus comandos imediatamente, e os erros podem ser corrigidos readily. prontamente. The biggest disadvantage comes when you want to share your programs with someone. A maior desvantagem quando voc quer compartilhar seus programas com algum. They must have the Eles devem ter a same interpreter, or you must have some way of giving it to them, and they need to understand how to use it. mesmo intrprete, ou voc deve ter alguma maneira de dar a eles, e eles precisam entender como us-lo. Also Tambm

users may not appreciate being thrown into a debugger if they press the wrong key! os usurios no podem apreciar a ser jogado em um depurador, se pressione a tecla errada! From a performance point of De um ponto de desempenho view, interpreters can use up a lot of memory, and generally do not generate code as efficiently as compilers. ver, os intrpretes podem usar uma grande quantidade de memria, e geralmente no geram cdigo de forma to eficiente como compiladores. In my opinion, interpreted languages are the best way to start if you have not done any programming before. Na minha opinio, linguagens interpretadas so a melhor maneira para comear, se voc no tiver feito qualquer tipo de programao antes. This Este kind of environment is typically found with languages like Lisp, Smalltalk, Perl and Basic. tipo de ambiente tipicamente encontrado com linguagens como Lisp, Smalltalk, Perl e Basic. It could also be argued Tambm poderia ser argumentado that the Unix shell ( que o shell Unix ( sh sh , , csh csh ) is itself an interpreter, and many people do in fact write shell scripts to help with ) por si s um intrprete, e muitas pessoas que, de facto, escrever shell "scripts" para ajudar com various housekeeping tasks on their machine. vrias tarefas "domsticas" em sua mquina. Indeed, part of the original Unix philosophy was to provide lots of De fato, parte da filosofia Unix original era fornecer lotes de small utility programs that could be linked together in shell scripts to perform useful tasks. pequenos programas utilitrios que podem ser ligados entre si em shell scripts para realizar tarefas teis. *5.3.2.* *5.3.2.* *Interpreters available with FreeBSD* *Intrpretes disponveis com FreeBSD* Here is a list of interpreters that are available as FreeBSD packages (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/), Aqui est uma lista de intrpretes que esto disponveis como pacotes do FreeBSD (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/) with a brief discussion of some of the more popular interpreted languages. com uma breve discusso de algumas das linguagens interpretadas mais populares. To get one of these packages, all you need to do is to click on the hotlink for the package, then run Para ganhar um destes pacotes, tudo que voc precisa fazer clicar sobre o link direto para o pacote, em seguida, execute # # *pkg_add /package name/* */nome do pacote/ pkg_add* as root. como root. Obviously, you will need to have a fully functional FreeBSD 2.1.0 or later system for the package to work! Obviamente, voc vai precisar ter um FreeBSD totalmente funcional 2.1.0 ou posterior do sistema para o pacote para o trabalho! BASIC BASIC Short for Beginner's All-purpose Symbolic Instruction Code. Curto para o All-purpose Symbolic Instruction Cdigo novato. Developed in the 1950s for teaching University Desenvolvido na dcada de 1950 para a Universidade de ensino students to program and provided with every self-respecting personal computer in the 1980s, BASIC has been estudantes para o programa e desde que com todos os computadores pessoais se preze na dcada de 1980, BASIC foi the first programming language for many programmers. a primeira linguagem de programao para muitos programadores. It's also the

foundation for Visual Basic. tambm a base para o Visual Basic. The Bywater Basic Interpreter (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/bwbasic-2.10.tgz) and the The Interpreter Bsico Bywater (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/bwbasic-2.10.tgz) eo Phil Cockroft's Basic Interpreter (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/pbasic-2.0.tgz) (formerly Intrprete Bsico de Phil Cockcroft (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/pbasic-2.0.tgz) (anteriormente Rabbit Basic) are available as FreeBSD FreeBSD packages (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/) Coelho Basic) esto disponveis como pacotes do FreeBSD FreeBSD (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/) /6/ /6/ -----------------------------------------------------------------------*Page 15* *Page 15* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ Lisp Cicio A language that was developed in the late 1950s as an alternative to the number-crunching languages that A linguagem que foi desenvolvida na dcada de 1950 como uma alternativa para as lnguas "nmero" que esmaga were popular at the time. eram populares na poca. Instead of being based on numbers, Lisp is based on lists; in fact the name is short for Em vez de se basear em nmeros, Lisp baseada em listas, na verdade o nome uma abreviao de List Processing. "Processamento List". Very popular in AI (Artificial Intelligence) circles. Muito popular na IA (Inteligncia Artificial) crculos. Lisp is an extremely powerful and sophisticated language, but can be rather large and unwieldy. Lisp uma linguagem extremamente poderosa e sofisticada, mas pode ser bastante grande e pesado. FreeBSD has GNU Common Lisp (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/gcl-2.0.tgz) available as a FreeBSD tem GNU Common Lisp (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/gcl-2.0.tgz) disponvel como um package. pacote. Perl Perl Very popular with system administrators for writing scripts; also often used on World Wide Web servers for Muito popular entre os administradores do sistema para a criao de scripts, tambm frequentemente usado em servidores World Wide Web para writing CGI scripts. escrever scripts CGI. The latest version (version 5) comes with FreeBSD. A ltima verso (verso 5) vem com FreeBSD. Scheme Esquema A dialect of Lisp that is rather more compact and cleaner than Common Lisp. Um dialeto de Lisp que um pouco mais compacto e mais limpo que Lisp Comum. Popular in Universities as it is Popular nas Universidades, pois simple enough to teach to undergraduates as a first language, while it has a high enough level of abstraction to simples o suficiente para ensinar aos estudantes como primeira lngua, enquanto ele tem um nvel bastante alto de abstrao para be used in research work. ser utilizado em trabalhos de investigao. FreeBSD has packages of the Elk Scheme Interpreter FreeBSD tem pacotes do regime Interpreter Elk (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/elk-3.0.tgz), the MIT Scheme Interpreter

(Ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/elk-3.0.tgz), o regime Interpreter MIT (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/mit-scheme-7.3.tgz) and the SCM Scheme Interpreter (Ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/mit-scheme-7.3.tgz) e do Sistema Interpreter SCM (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/scm-4e1.tgz). (Ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/scm-4e1.tgz). Icon cone The Icon Programming Language (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/icon-9.0.tgz). A Linguagem de Programao Icon (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/icon-9.0.tgz). Logo Logotipo Brian Harvey's LOGO Interpreter (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/ucblogo-3.3.tgz). Intrprete LOGO de Brian Harvey (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/ucblogo-3.3.tgz). Python Pton The Python Object-Oriented Programming Language O Python Object-Oriented Programming Language (ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/python-1.2) (Ftp://ftp.FreeBSD.org:pub/FreeBSD/packages/lang/python-1.2) /7/ /7/ -----------------------------------------------------------------------*Page 16* *Page 16* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ *5.3.3.* *5.3.3.* *Compilers* *Compiladores* Compilers are rather different. Compiladores so bastante diferentes. First of all, you write your code in a file (or files) using an editor. Primeiro de tudo, voc escreve seu cdigo em um arquivo (ou arquivos), utilizando um editor. You then run the Em seguida, execute o compiler and see if it accepts your program. compilador e ver se ele aceita o seu programa. If it did not compile, grit your teeth and go back to the editor; if it did Se no compilar, ranger os dentes e voltar ao editor e, se ele fez compile and gave you a program, you can run it either at a shell command prompt or in a debugger to see if it works compilar e deu-lhe um programa, voc pode execut-lo em um prompt de comando shell ou um depurador para ver se funciona properly. adequadamente. 1 1 Obviously, this is not quite as direct as using an interpreter. Obviamente, isso no to direta como a utilizao de um intrprete. However it allows you to do a lot of things which are No entanto, permite que voc faa um monte de coisas que so very difficult or even impossible with an interpreter, such as writing code which interacts closely with the operating muito difcil ou mesmo impossvel para um intrprete, como escrever cdigo que interage de perto com a operao systemor even writing your own operating system! sistema, ou mesmo escrever o seu prprio sistema operacional! It's also useful if you need to write very efficient code, as the Tambm til se voc precisar escrever cdigo muito eficiente, como o compiler can take its time and optimise the code, which would not be acceptable in an interpreter. compilador pode tomar o seu tempo e optimizar o cdigo, o que no seria aceitvel um intrprete. And distributing a E distribuir um program written for a compiler is usually more straightforward than one

written for an interpreteryou can just give programa escrito para um compilador geralmente mais simples do que um escrito de um intrprete, voc pode apenas dar them a copy of the executable, assuming they have the same operating system as you. -lhes uma cpia do executvel, assumindo que eles tm o mesmo sistema operacional que voc. Compiled languages include Pascal, C and C++. Linguagens compiladas incluem Pascal, C e C + +. C and C++ are rather unforgiving languages, and best suited to C e C + + so linguagens bastante implacvel e mais adequado para more experienced programmers; Pascal, on the other hand, was designed as an educational language, and is quite a programadores mais experientes, Pascal, por outro lado, foi concebida como uma linguagem educacional, e bastante good language to start with. boa linguagem para comear. Unfortunately, FreeBSD doesn't have any Pascal support, except for a Pascal-to-C Infelizmente, FreeBSD no tem qualquer apoio Pascal, com exceo de um Pascal-to-C converter in the ports. conversor nos portos. As the edit-compile-run-debug cycle is rather tedious when using separate programs, many commercial compiler Como o ciclo de edio-compilao-run-debug bastante tedioso quando usar programas separados, muitos compilador comercial makers have produced Integrated Development Environments (IDEs for short). fabricantes tm produzido ambientes de desenvolvimento integrado (IDEs para o short). FreeBSD does not have an IDE as FreeBSD no tem um IDE como such; however it is possible to use Emacs for this purpose. tal, no entanto, possvel utilizar o Emacs para esta finalidade. This is discussed in Section 5.7 . Isso discutido na Seo 5.7 . *5.4.* *5.4.* *Compiling with* *Compilando com* *cc* *cc* This section deals only with the GNU compiler for C and C++, since that comes with the base FreeBSD system. Esta seo lida apenas com o compilador GNU para C e C + +, uma vez que vem com o sistema FreeBSD base. It Ele can be invoked by either pode ser invocada por qualquer cc cc or ou gcc gcc . . The details of producing a program with an interpreter vary considerably Os pormenores da produo de um programa com um intrprete variar consideravelmente between interpreters, and are usually well covered in the documentation and on-line help for the interpreter. entre os intrpretes, e geralmente so bem cobertos na documentao e ajuda on-line para o intrprete. Once you've written your masterpiece, the next step is to convert it into something that will (hopefully!) run on Depois que voc escreveu sua obra-prima, o prximo passo convert-lo em algo que (com sorte) executado em FreeBSD. FreeBSD. This usually involves several steps, each of which is done by a separate program. Isto geralmente envolve vrios passos, cada um dos quais feito por um programa distinto. 1. 1. Pre-process your source code to remove comments and do other tricks like expanding macros in C. Pr-processar o seu cdigo-fonte para remover comentrios e fazer outros truques como expandir macros em C. 2. 2. Check the syntax of your code to see if you have obeyed the rules of the language. Verifique a sintaxe do seu cdigo para ver se voc tiver obedecido s regras do idioma. If you have not, it will Se voc no tiver, ele vai

complain! reclamar! 3. 3. Convert the source code into assembly languagethis is very close to machine code, but still understandable by Converter o cdigo fonte em linguagem assembly, este est muito perto de cdigo de mquina, mas ainda assim compreensvel por humans. seres humanos. Allegedly. Alegadamente. 2 2 4. 4. Convert the assembly language into machine codeyep, we are talking bits and bytes, ones and zeros here. Converter a linguagem de montagem em cdigo de mquina, sim, estamos a falar de bits e bytes, uns e zeros aqui. /8/ /8/ -----------------------------------------------------------------------*Page 17* *Page 17* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ 5. 5. Check that you have used things like functions and global variables in a consistent way. Verifique se voc usou coisas como funes e variveis globais de uma forma consistente. For example, if you Por exemplo, se have called a non-existent function, it will complain. ter chamado uma funo inexistente, ele vai reclamar. 6. 6. If you are trying to produce an executable from several source code files, work out how to fit them all together. Se voc est tentando produzir um executvel a partir de vrios arquivos de cdigo fonte, o trabalho como encaix-los todos juntos. 7. 7. Work out how to produce something that the system's run-time loader will be able to load into memory and run. Exercite-se como produzir algo que carregador de tempo de execuo do sistema ser capaz de carregar na memria e executado. 8. 8. Finally, write the executable on the file system. Finalmente, escreva o executvel no sistema de arquivos. The word /compiling/ is often used to refer to just steps 1 to 4the others are referred to as /linking/ . A palavra /compilao/ frequentemente utilizado para referir apenas os passos 1 a 4 os outros so referidos como /ligando./ Sometimes step 1 s vezes passo 1 is referred to as /pre-processing/ and steps 3-4 as /assembling/ . referido como /pr-processamento/ e os passos 3-4 como /a montagem./ Fortunately, almost all this detail is hidden from you, as Felizmente, quase todos esses detalhes est escondido de voc, como cc cc is a front end that manages calling all these programs um front-end que gerencia chamando todos esses programas with the right arguments for you; simply typing com os argumentos certos para voc, basta digitar % % *cc foobar.c* *cc foobar.c* will cause causar foobar.c foobar.c to be compiled by all the steps above. ser elaboradas por todos os passos acima. If you have more than one file to compile, just do Se voc tiver mais de um arquivo para compilar, basta fazer something like algo parecido % % *cc foo.c bar.c* *cc foo.c bar.c* Note that the syntax checking is just thatchecking the syntax. Note-se que a verificao de sintaxe exatamente isso, a verificao da sintaxe. It will not check for any logical mistakes you may No vai verificar se h erros lgicos Voc pode have made, like putting the program into an infinite loop, or using a

bubble sort when you meant to use a binary sort. ter feito, como colocar o programa em um loop infinito, ou usando uma espcie de bolha quando voc pretende usar uma classificao binria. 3 3 There are lots and lots of options for H muitas e muitas opes para cc cc , which are all in the man page. , Que esto todos na pgina man. Here are a few of the most important ones, Aqui esto algumas das mais importantes, with examples of how to use them. com exemplos de como us-los. -o /filename/ -O /nome do arquivo/ The output name of the file. O nome de sada do arquivo. If you do not use this option, Se voc no usar esta opo, cc cc will produce an executable called vai produzir um executvel chamado a.out a.out . . 4 4 % % *cc foobar.c* *cc foobar.c* /executable is/ /executvel / /a.out/ /a.out/ % % *cc -o foobar foobar.c* *cc-o foobar.c foobar* /executable is/ /executvel / /foobar/ /foobar/ -c -C Just compile the file, do not link it. Apenas compilar o arquivo, no lig-lo. Useful for toy programs where you just want to check the syntax, or if you til para programas de brinquedos onde voc quer apenas verificar a sintaxe, ou se voc are using a estiver usando uma Makefile Makefile . . % % *cc -c foobar.c* *cc-c foobar.c* /9/ /9/ -----------------------------------------------------------------------*Page 18* *Page 18* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ This will produce an /object file/ (not an executable) called Isso ir produzir um /arquivo de objeto/ (e no um executvel) chamado foobar.o foobar.o . . This can be linked together with other Isto pode estar ligado em conjunto com outros object files into an executable. arquivos objeto em um arquivo executvel. -g -G Create a debug version of the executable. Criar uma verso de depurao do executvel. This makes the compiler put information into the executable about Isso faz com que o compilador colocar informaes no executvel sobre which line of which source file corresponds to which function call. qual a linha que corresponde arquivo de origem para que chamar a funo. A debugger can use this information to show Um depurador pode usar esta informao para mostrar the source code as you step through the program, which is /very/ useful; the disadvantage is that all this extra o cdigo-fonte como voc pisa atravs do programa, que /muito/ til, a desvantagem que tudo isso adicional

information makes the program much bigger. faz com que o programa de informao muito maior. Normally, you compile with Normalmente, voc compilar com -g -G while you are developing a enquanto voc estiver desenvolvendo um program and then compile a release version without programa e, em seguida, compilar uma verso "release" sem -g -G when you're satisfied it works properly. Quando estiver satisfeito ele funciona corretamente. % % *cc -g foobar.c* *cc-g foobar.c* This will produce a debug version of the program. Isso vai produzir uma verso de depurao do programa. 5 5 -O -O Create an optimised version of the executable. Criar uma verso otimizada do executvel. The compiler performs various clever tricks to try and produce O compilador executa vrios truques espertos para tentar produzir an executable that runs faster than normal. um executvel que mais rpido que o normal. You can add a number after the Voc pode adicionar um nmero aps o -O -O to specify a higher level of para especificar um nvel mais elevado de optimisation, but this often exposes bugs in the compiler's optimiser. otimizao, mas isso muitas vezes expe erros no otimizador do compilador. For instance, the version of Por exemplo, a verso cc cc that comes que vem with the 2.1.0 release of FreeBSD is known to produce bad code with the com a verso 2.1.0 do FreeBSD conhecida por produzir cdigo ruim com o -O2 -O2 option in some circumstances. opo em algumas circunstncias. Optimisation is usually only turned on when compiling a release version. Optimizao normalmente s ativado quando compilar uma verso de lanamento. % % *cc -O -o foobar foobar.c* *cc-O-O foobar foobar.c* This will produce an optimised version of Isso vai produzir uma verso otimizada do foobar foobar . . The following three flags will force Os trs seguintes bandeiras forar cc cc to check that your code complies to the relevant international standard, often para verificar se o seu cdigo est em conformidade com a norma internacional relevante, muitas vezes referred to as the ANSI standard, though strictly speaking it is an ISO standard. referida como a norma ANSI, embora estritamente falando, uma norma da ISO. -Wall -Wall Enable all the warnings which the authors of Ativar todos os avisos que os autores cc cc believe are worthwhile. acreditar valem a pena. Despite the name, it will not enable all Apesar do nome, no ir permitir que todos the warnings as advertncias cc cc is capable of. capaz de suportar.

/10/ /10/ -----------------------------------------------------------------------*Page 19* *Page 19* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ -ansi -Ansi Turn off most, but not all, of the non-ANSI C features provided by Desactivar a maioria, mas no todas, as caractersticas no-ANSI C fornecidas pelos cc cc . . Despite the name, it does not guarantee Apesar do nome, ele no garante strictly that your code will comply to the standard. rigorosamente que seu cdigo ir cumprir a norma. -pedantic -Pedante Turn off /all/ Desligue /todos os/ cc cc 's non-ANSI C features. 'S recursos no-ANSI C. Without these flags, Sem essas bandeiras, cc cc will allow you to use some of its non-standard extensions to the standard. permitir que voc use algumas de suas extenses no-padro para o padro. Some of these are Alguns destes so very useful, but will not work with other compilersin fact, one of the main aims of the standard is to allow people muito til, mas no funcionar com outros compiladores-de fato, um dos principais objetivos da norma permitir que as pessoas to write code that will work with any compiler on any system. escrever cdigo que ir funcionar com qualquer compilador em qualquer sistema. This is known as /portable code/ . Isto conhecido como /o cdigo porttil./ Generally, you should try to make your code as portable as possible, as otherwise you may have to completely Geralmente, voc deve tentar fazer o seu cdigo mais portvel possvel, caso contrrio, voc pode ter que completamente re-write the program later to get it to work somewhere elseand who knows what you may be using in a few years re-escrever o programa mais tarde para faz-lo trabalhar em outro lugar e que sabe o que voc pode estar usando em poucos anos time? tempo? % % *cc -Wall -ansi -pedantic -o foobar foobar.c* *cc-Wall-ansi-pedante-o foobar.c foobar* This will produce an executable Isso ir produzir um executvel foobar foobar after checking depois de verificar foobar.c foobar.c for standard compliance. para o cumprimento das normas. -l /library/ /Biblioteca-l/ Specify a function library to be used during when linking. Especifique uma biblioteca de funes para ser usado durante quando ligar. The most common example of this is when compiling a program that uses some of the mathematical functions O exemplo mais comum quando a compilao de um programa que usa algumas das funes matemticas in C. Unlike most other platforms, these are in a separate library from the standard C one and you have to tell em C. Ao contrrio da maioria de outras plataformas, estes esto em uma biblioteca separada do padro C e um que voc tem a dizer the compiler to add it. o compilador para adicion-lo. The rule is that if the library is called A regra que se a biblioteca chamado

lib /something/ .a lib /alguma coisa./ uma , you give , Voc d cc cc the argument o argumento -l /something/ -L /algo/ . . For Para example, the math library is exemplo, a biblioteca matemtica libm.a libm.a , so you give , Ento voc d cc cc the argument o argumento -lm -Lm . . A common gotcha with the math A "pegadinha" comum com a matemtica library is that it has to be the last library on the command line. biblioteca que tem que ser a ltima biblioteca na linha de comando. % % *cc -o foobar foobar.c -lm* *cc-o foobar foobar.c-lm* This will link the math library functions into Isto ir ligar as funes de biblioteca de matemtica em foobar foobar . . If you are compiling C++ code, you need to add Se voc est compilando o cdigo C + +, voc precisa adicionar -lg++ -Lg + + , or Ou -lstdc++ -Lstdc + + if you are using FreeBSD 2.2 or later, to se voc estiver usando FreeBSD 2.2 ou posterior, para the command line argument to link the C++ library functions. o argumento de linha de comando para ligar as funes C + + biblioteca. Alternatively, you can run Alternativamente, voc pode executar c++ c + + instead of em vez de cc cc , , which does this for you. que faz isso para voc. c++ c + + can also be invoked as tambm pode ser invocado como g++ g+ + on FreeBSD. em FreeBSD. % % *cc -o foobar foobar.cc -lg++* *cc-o foobar foobar.cc-lg + +* /For FreeBSD 2.1.6 and earlier/ /Para o FreeBSD 2.1.6 e anteriores/ % % *cc -o foobar foobar.cc -lstdc++* /For FreeBSD 2.2 and later/ *cc-o foobar foobar.cc-lstdc + +* /Para o FreeBSD 2.2 e mais tarde/ % % *c++ -o foobar foobar.cc* *c + +-o foobar foobar.cc* /11/ /11/ -----------------------------------------------------------------------*Page 20* *Page 20* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ Each of these will both produce an executable Cada um destes ir produzir tanto um executvel foobar foobar from the C++ source file a partir do arquivo fonte C + + foobar.cc foobar.cc . . Note that, on Unix Note-se que, em Unix systems, C++ source files traditionally end in sistemas, C + + arquivos

de origem tradicionalmente termina em .C . C , , .cxx . CXX or ou .cc . Cc , rather than the MS-DOS style , Em vez do modelo MS-DOS .cpp . Cpp (which was (Que era already used for something else). j utilizado para outra coisa). gcc gcc used to rely on this to work out what kind of compiler to use on the usado para contar com este trabalho que tipo de compilador para usar no source file; however, this restriction no longer applies, so you may now call your C++ files arquivo de origem, no entanto, esta restrio no se aplica mais, ento agora voc pode chamar seus arquivos C + + .cpp . Cpp with impunity! impunemente! *5.4.1.* *5.4.1.* *Common* *Comum* *cc* *cc* *Queries and Problems* *Consultas e Problemas* *1.* I am trying to write a program which uses the *1.* Estou tentando escrever um programa que usa o sin() sin () function and I get an error like this. funcionar e eu recebo um erro como este. What does it mean? O que isso significa? /var/tmp/cc0143941.o: Undefined symbol '_sin' referenced from text segment / Var/tmp/cc0143941.o: smbolo Undefined "_sin 'referenciado a partir de segmento de texto When using mathematical functions like Ao usar funes matemticas como sin() sin () , you have to tell , Voc tem que dizer cc cc to link in the math library, like so: de ligao na biblioteca de matemtica, assim: % % *cc -o foobar foobar.c -lm* *cc-o foobar foobar.c-lm* *2.* All right, I wrote this simple program to practice using *2.* Tudo bem, eu escrevi este programa simples para praticar o uso de -lm -Lm . . All it does is raise 2.1 to the power of 6. Tudo que faz levantar 2.1 para o poder da 6. #include < stdio.h > # Include int main() { int main () { float f; flutuar f; f = pow(2.1, 6); f = pow (2.1, 6); printf("2.1 ^ 6 = %f\n", f); printf ("2.1 ^ 6 =% f \ n", f); return 0; retornar 0; } } and I compiled it as: e eu compilei como: % % *cc temp.c -lm* *cc temp.c-lm* like you said I should, but I get this when I run it: como voc disse que eu deveria, mas eu recebo isso quando eu execut-lo: /12/ /12/ -----------------------------------------------------------------------*Page 21* *Page 21* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ % %

*./a.out* *. / A.out* 2.1 ^ 6 = 1023.000000 2.1 ^ 6 = 1023,000000 This is /not/ the right answer! Esta /no/ a resposta certa! What is going on? O que est acontecendo? When the compiler sees you call a function, it checks if it has already seen a prototype for it. Quando o compilador v voc chamar uma funo, ele verifica se ele j viu um prottipo para ele. If it has not, it assumes Se no tiver, ele assume the function returns an int, which is definitely not what you want here. a funo retorna um int, o que definitivamente no o que voc quer aqui. *3.* So how do I fix this? *3.* Ento, como fao para corrigir isso? The prototypes for the mathematical functions are in Os prottipos para as funes matemticas so em math.h math.h . . If you include this file, the compiler will be able to Se voc incluir esse arquivo, o compilador ser capaz de find the prototype and it will stop doing strange things to your calculation! encontrar o prottipo e ele vai parar de fazer coisas estranhas para o seu clculo! #include < math.h > # Include #include < stdio.h > # Include int main() { int main () { ... ... After recompiling it as you did before, run it: Depois de recompilar-lo como voc fez antes, execut-lo: % % *./a.out* *. / A.out* 2.1 ^ 6 = 85.766121 2.1 ^ 6 = 85,766121 If you are using any of the mathematical functions, /always/ include Se voc estiver usando qualquer uma das funes matemticas, /inclua sempre/ math.h math.h and remember to link in the math library. e lembre-se de vincular a biblioteca matemtica. *4.* I compiled a file called *4.* Que eu compilei um arquivo chamado foobar.c foobar.c and I cannot find an executable called e eu no consigo encontrar um executvel chamado foobar foobar . . Where's it gone? Onde que ele foi? Remember, Lembre-se, cc cc will call the executable vai chamar o executvel a.out a.out unless you tell it differently. a menos que voc diga a ele de forma diferente. Use the Use o -o /filename/ -O /nome do arquivo/ option: opo: % % *cc -o foobar foobar.c* *cc-o foobar.c foobar* *5.* OK, I have an executable called *5.* Bem, eu tenho um executvel chamado foobar foobar , I can see it when I run , Eu posso v-la quando eu corro ls ls , but when I type in , Mas quando eu digitar foobar foobar at the command no comando prompt it tells me there is no such file. pedir ele me diz que no h tal arquivo. Why can it not find it? Por que pode no encontr-lo? Unlike MS-DOS, Unix does not look in the current directory when it is

trying to find out which executable you want Ao contrrio do MS-DOS, Unix no olha no diretrio atual quando se est tentando descobrir qual executvel que voc deseja it to run, unless you tell it to. que ele seja executado, a menos que voc diga a ele. Either type Qualquer tipo ./foobar . / Foobar , which means run the file called , Que significa "executar o arquivo chamado foobar foobar in the current na actual directory, or change your PATH environment variable so that it looks something like diretrio ", ou alterar a varivel de ambiente PATH para que ele se parece com /13/ /13/ -----------------------------------------------------------------------*Page 22* *Page 22* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ bin:/usr/bin:/usr/local/bin:. bin :/ usr / bin :/ usr / local / bin:. The dot at the end means look in the current directory if it is not in any of the others. O ponto no final significa "olhar no diretrio atual, se no em qualquer um dos outros." *6.* I called my executable *6.* Liguei para o meu executvel test teste , but nothing happens when I run it. , Mas nada acontece quando eu execut-lo. What is going on? O que est acontecendo? Most Unix systems have a program called A maioria dos sistemas Unix tem um programa chamado test teste in em /usr/bin / Usr / bin and the shell is picking that one up before it gets to eo escudo escolher aquele up antes de chegar a checking the current directory. verificar o diretrio atual. Either type: Qualquer tipo: % % *./test* *. / Teste* or choose a better name for your program! ou escolher um nome melhor para o seu programa! *7.* I compiled my program and it seemed to run all right at first, then there was an error and it said something about *7.* Que eu compilei meu programa e ele parecia correr tudo bem no incio, em seguida, houve um erro e ele disse algo sobre core dumped ncleo despejado . . What does that mean? O que significa isso? The name /core dump/ dates back to the very early days of Unix, when the machines used core memory for storing O /ncleo de despejo/ nome remonta aos primrdios do Unix, quando as mquinas usadas da memria principal para armazenamento data. dados. Basically, if the program failed under certain conditions, the system would write the contents of core memory Basicamente, se o programa falhou sob certas condies, o sistema iria escrever o contedo da memria de ncleo to disk in a file called para o disco em um arquivo chamado core ncleo , which the programmer could then pore over to find out what went wrong. , Que o programador pode ento debruar sobre para descobrir o que deu errado. *8.* Fascinating stuff, but what I am supposed to do now? *8.* Coisa fascinante, mas o que eu devo fazer agora?

Use Usar gdb gdb to analyse the core (see Section 5.6) . para analisar o ncleo (ver Seo 5.6) . *9.* When my program dumped core, it said something about a *9.* Ao meu programa despejado ncleo, ele disse algo sobre um segmentation fault falha de segmentao . . What's that? O que isso? This basically means that your program tried to perform some sort of illegal operation on memory; Unix is designed Isto significa basicamente que o seu programa tentou realizar algum tipo de operao ilegal em memria; Unix foi projetado to protect the operating system and other programs from rogue programs. para proteger o sistema operacional e outros programas de programas maliciosos. Common causes for this are: As causas mais comuns para isso so: Trying to write to a NULL pointer, eg Tentando escrever para um ponteiro NULL, por exemplo, char *foo = NULL; char * foo = NULL; strcpy(foo, "bang!"); strcpy (foo, "bang!"); Using a pointer that hasn't been initialised, eg Usando um ponteiro que no tenha sido iniciada, por exemplo, char *foo; char * foo; strcpy(foo, "bang!"); strcpy (foo, "bang!"); /14/ /14/ -----------------------------------------------------------------------*Page 23* *Page 23* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ The pointer will have some random value that, with luck, will point into an area of memory that isn't available to O ponteiro vai ter algum valor aleatrio que, com sorte, ir apontar para uma rea de memria que no est disponvel para your program and the kernel will kill your program before it can do any damage. seu programa eo kernel vai matar o seu programa antes que ele possa fazer qualquer dano. If you're unlucky, it'll point Se voc azarado, ele vai apontar somewhere inside your own program and corrupt one of your data structures, causing the program to fail em algum lugar dentro do seu prprio programa e corrupto uma das suas estruturas de dados, fazendo com que o programa falhar mysteriously. misteriosamente. Trying to access past the end of an array, eg Tentativa de acesso aps o final de uma matriz, por exemplo, int bar[20]; bar int [20]; bar[27] = 6; bar [27] = 6; Trying to store something in read-only memory, eg Tentar armazenar algo na memria s de leitura, por exemplo, char *foo = "My string"; char * foo = "Minha string"; strcpy(foo, "bang!"); strcpy (foo, "bang!"); Unix compilers often put string literals like Compiladores Unix muitas vezes colocar strings literais como "My string" "Minha string" into read-only areas of memory. em somente leitura reas de memria. Doing naughty things with Fazer as coisas impertinentes com

malloc() malloc () and e free() free () , eg , Por exemplo, char bar[80]; carvo bar [80]; free(bar); livre (bar); or ou char *foo = malloc(27); char * foo = malloc (27); free(foo); livre (foo); free(foo); livre (foo); Making one of these mistakes will not always lead to an error, but they are always bad practice. Fazendo um desses erros nem sempre vai levar a um erro, mas eles esto sempre m prtica. Some systems and Alguns sistemas e compilers are more tolerant than others, which is why programs that ran well on one system can crash when you try compiladores so mais tolerantes do que outros, razo pela qual os programas que funcionaram bem em um sistema pode falhar quando voc tentar them on an another. los em uma outra. /15/ /15/ -----------------------------------------------------------------------*Page 24* *Page 24* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ *10.* Sometimes when I get a core dump it says *10.* s vezes, quando eu recebo um dump de memria que diz bus error erro de nibus . . It says in my Unix book that this means a hardware Diz no meu livro Unix que isso significa um hardware problem, but the computer still seems to be working. problema, mas ainda assim o computador parece estar funcionando. Is this true? Isso verdade? No, fortunately not (unless of course you really do have a hardware problem...). No, felizmente no (a menos que voc realmente tem um problema de hardware ...). This is usually another way of Este normalmente um outro modo de saying that you accessed memory in a way you shouldn't have. dizendo que voc acessou a memria de uma forma que no deveria ter. *11.* This dumping core business sounds as though it could be quite useful, if I can make it happen when I want to. *11.* Esse negcio de ncleo de dumping soa como se ele poderia ser bastante til, se eu posso fazer isso acontecer quando eu quiser. Can I do this, or do I have to wait until there's an error? Eu posso fazer isso, ou eu tenho que esperar at que haja um erro? Yes, just go to another console or xterm, do Sim, basta ir para outro console ou xterm, fazer % % *ps* *ps* to find out the process ID of your program, and do para descobrir a ID de seu programa de processo e fazer % % *kill -ABRT /pid/* *mat-ABRT /pid/* where /pid/ is the process ID you looked up. onde /pid/ o ID do processo que voc olhou para cima. This is useful if your program has got stuck in an infinite loop, for instance. Isto til se o seu programa ficou preso em um loop infinito, por exemplo. If your program happens to trap Se o seu programa acontece para prender SIGABRT, there are several other signals which have a similar effect. SIGABRT, existem vrios outros sinais, que tm um efeito semelhante. Alternatively, you can create a core dump from inside your program, by

calling the Alternativamente, voc pode criar um dump de memria de dentro do seu programa, chamando a abort() abort () function. funo. See the man Veja o homem page of abort(3) to learn more. Pgina de abortar (3) para saber mais. If you want to create a core dump from outside your program, but don't want the process to terminate, you can use Se voc deseja criar um dump de memria fora do seu programa, mas no quer que o processo terminar, voc pode usar the o gcore gcore program. programa. See the man page of gcore(1) for more information. Veja a pgina de manual de gcore (1) para obter mais informaes. *5.5.* *5.5.* *Make* *Fazer* *5.5.1.* *5.5.1.* *What is* *O que * *make* *fazer* *?* *?* When you're working on a simple program with only one or two source files, typing in Quando voc est trabalhando em um programa simples, com apenas um ou dois arquivos de origem, digitando % % *cc file1.c file2.c* *cc file1.c FILE2.C* is not too bad, but it quickly becomes very tedious when there are several filesand it can take a while to compile, no to ruim, mas rapidamente se torna muito chato quando h vrios arquivos e pode demorar um pouco para compilar too. tambm. /16/ /16/ -----------------------------------------------------------------------*Page 25* *Page 25* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ One way to get around this is to use object files and only recompile the source file if the source code has changed. Uma maneira de contornar este problema usar arquivos de objetos e apenas recompilar o arquivo de origem se o cdigo-fonte foi alterada. So Assim we could have something like: poderamos ter algo como: % % *cc file1.o file2.o* ... *file37.c* ... *cc arq1.o arq2.o* ... *file37.c* ... if we'd changed se tivssemos mudado file37.c file37.c , but not any of the others, since the last time we compiled. , Mas no qualquer um dos outros, j que a ltima vez que compilado. This may speed up the Isto pode acelerar o compilation quite a bit, but doesn't solve the typing problem. compilao um pouco, mas no resolve o problema de digitao. Or we could write a shell script to solve the typing problem, but it would have to re-compile everything, making it Ou poderamos escrever um script shell para resolver o problema de digitao, mas que teria de voltar a compilar tudo, tornando-se very inefficient on a large project. muito ineficiente em um grande projeto. What happens if we have hundreds of source files lying about? O que acontece se temos centenas de arquivos de origem mentindo? What if we're working in a team with other people E se ns estamos trabalhando em uma equipe com outras pessoas who forget to tell us when they've changed one of their source files that we use? que se esquea de nos dizer quando eles mudaram um dos seus arquivos de origem que usamos?

Perhaps we could put the two solutions together and write something like a shell script that would contain some kind Talvez pudssemos colocar as duas solues em conjunto e escrever algo como um script shell que contm algum tipo of magic rule saying when a source file needs compiling. de regra mgica dizer quando um arquivo de origem precisa de compilar. Now all we need now is a program that can understand Agora, tudo o que precisamos agora um programa que pode compreender these rules, as it's a bit too complicated for the shell. estas regras, pois um pouco complicado para o shell. This program is called Este programa chamado make fazer . . It reads in a file, called a /makefile/ , that tells it how different files depend on each other, Ele l um arquivo, chamado /makefile,/ que diz-lhe como arquivos diferentes dependem uns dos outros, and works out which files need to be re-compiled and which ones don't. e funciona quais arquivos precisam ser re-compilado e quais no. For example, a rule could say something like Por exemplo, uma regra poderia dizer algo como if "Se fromboz.o fromboz.o is older than mais velho do que fromboz.c fromboz.c , that means someone must have changed , Isso significa que algum deve ter mudado fromboz.c fromboz.c , so it needs to be , Por isso precisa ser re-compiled. The makefile also has rules telling make /how/ to re-compile the source file, making it a much more re-compilado. "O makefile tambm tem regras que dizem /como/ fazer para voltar a compilar o arquivo de origem, tornando-se muito mais powerful tool. ferramenta poderosa. Makefiles are typically kept in the same directory as the source they apply to, and can be called Makefiles so normalmente mantidos no mesmo diretrio que a fonte se aplicam a, e pode ser chamado makefile makefile , , Makefile Makefile or ou MAKEFILE MAKEFILE . . Most programmers use the name A maioria dos programadores usam o nome Makefile Makefile , as this puts it near the top of a directory , Pois isso coloca-lo perto do topo de um diretrio listing, where it can easily be seen. perfil, onde ele pode ser facilmente visto. 6 6 *5.5.2.* *5.5.2.* *Example of using* *Exemplo de utilizao* *make* *fazer* Here's a very simple make file: Aqui est um arquivo make muito simples: foo: foo.c foo: foo.c cc -o foo foo.c cc-o foo foo.c It consists of two lines, a dependency line and a creation line. composto por duas linhas, uma linha de dependncia e uma linha de criao. The dependency line here consists of the name of the program (known as the /target/ ), followed by a colon, then A linha de dependncia aqui consiste no nome do programa (conhecido como o /alvo),/ seguido de um clon, ento whitespace, then the name of the source file. espaos em branco, em seguida, o nome do arquivo de origem. When Quando

make fazer reads this line, it looks to see if l essa linha, olha para ver se foo foo exists; if it exists, it existe e, se ele existe, compares the time compara a hora foo foo was last modified to the time foi modificada para o ltimo momento foo.c foo.c was last modified. foi modificada pela ltima vez. If Se foo foo does not exist, or is older than no existe, ou mais velho do que foo.c foo.c , it then looks at the creation line to find out what to do. , Ento ele olha para a linha de criao para descobrir o que fazer. In other words, this is the rule for working out when Em outras palavras, esta a regra para trabalhar fora quando foo.c foo.c needs to be re-compiled. precisa ser re-compilado. /17/ /17/ -----------------------------------------------------------------------*Page 26* *Page 26* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ The creation line starts with a tab (press the *tab* key) and then the command you would type to create A linha de criao comea com um guia (pressione a tecla *tab)* e, em seguida, o comando que voc deve digitar para criar foo foo if you se voc were doing it at a command prompt. estavam fazendo isso em um prompt de comando. If Se foo foo is out of date, or does not exist, est desatualizado, ou no existe, make fazer then executes this command to em seguida, executa o comando para create it. cri-lo. In other words, this is the rule which tells make how to re-compile Em outras palavras, esta a regra que diz como fazer para voltar a compilar foo.c foo.c . . So, when you type *make* , it will make sure that Ento, quando voc digita *fazer,* ele vai ter certeza de que foo foo is up to date with respect to your latest changes to est atualizado com relao a suas ltimas alteraes foo.c foo.c . . This Este principle can be extended to princpio pode ser alargado a Makefile Makefile s with hundreds of targetsin fact, on FreeBSD, it is possible to compile the s com centenas de alvos em verdade, em FreeBSD, possvel compilar a entire operating system just by typing *make world* in the appropriate directory! todo o sistema operacional apenas digitando *make world* no diretrio apropriado! Another useful property of makefiles is that the targets don't have to be programs. Outra propriedade til da makefiles que os alvos no precisam ser programas. For instance, we could have a Por exemplo, poderamos ter um make file that looks like this: fazer arquivo que se parece com isto:

foo: foo.c foo: foo.c cc -o foo foo.c cc-o foo foo.c install: instalar: cp foo /home/me cp foo / home / me We can tell make which target we want to make by typing: Podemos dizer que fazer-alvo que queremos fazer, digitando: % % *make /target/* *tornar /alvo/* make fazer will then only look at that target and ignore any others. ento s olhar para o alvo e ignorar os outros. For example, if we type *make foo* with the makefile Por exemplo, se digitar *fazer foo* com o makefile above, make will ignore the install target. acima, faa ir ignorar o destino de instalao. If we just type *make* on its own, make will always look at the first target and then stop without looking at any others. Se digitar apenas *fazer* por conta prpria, certifique-se sempre olhar para o primeiro alvo e depois parar, sem olhar para os outros. So if we typed *make* here, it will just go to the foo target, re-compile Ento, se ns digitamos *fazer* aqui, ele s vai para o alvo foo, re-compilao foo foo if necessary, and then stop without going se necessrio, e depois parar, sem passar on to the install target. para a meta de instalao. Notice that the install target doesn't actually depend on anything! Note-se que a meta de instalao na verdade no depende de nada! This means that the command on the following line Isso significa que o comando na linha seguinte is always executed when we try to make that target by typing *make install* . sempre executada quando tentamos fazer com que essa meta o comando *make install.* In this case, it will copy Neste caso, ele copia foo foo into em the user's home directory. o diretrio home do usurio. This is often used by application makefiles, so that the application can be installed in the Isso muitas vezes utilizado por aplicao makefiles, de modo que a aplicao pode ser instalada no correct directory when it has been correctly compiled. corrigir diretrio quando foi compilado corretamente. This is a slightly confusing subject to try and explain. Este um assunto um pouco confuso para tentar explicar. If you don't quite understand how Se voc no consegue entender como make fazer works, the best thing obras, a melhor coisa to do is to write a simple program like hello world and a make file like the one above and experiment. a fazer escrever um programa simples, como "Ol mundo" e fazer um arquivo como o descrito acima e experincia. Then Em seguida progress to using more than one source file, or having the source file include a header file. progredir para usar mais de um arquivo de origem, ou com o arquivo de origem incluir um arquivo de cabealho. The O touch tocar command is comando very useful hereit changes the date on a file without you having to edit it. muito til aqui, ele muda a data em um arquivo sem a necessidade de edit-lo. *5.5.3.* *5.5.3.* *Make and include-files* *Faa e incluem-arquivos* C code often starts with a list of files to include, for example stdio.h. Cdigo C muitas vezes comea com uma lista de arquivos para

incluir, por exemplo stdio.h. Some of these files are system-include files, Alguns destes arquivos so do sistema incluem-arquivos, some of them are from the project you're now working on: alguns deles so do projeto que voc est trabalhando agora em: /18/ /18/ -----------------------------------------------------------------------*Page 27* *Page 27* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ #include < stdio.h > # Include #include "foo.h" # Include "foo.h" int main(.... int main (.... To make sure that this file is recompiled the moment Para certificar-se de que este arquivo recompilado o momento foo.h foo.h is changed, you have to add it in your for alterado, voc tem que adicion-lo em seu Makefile Makefile : : foo: foo.c foo.h foo: foo.c foo.h The moment your project is getting bigger and you have more and more own include-files to maintain, it will be a No momento em que o projeto est ficando maior e voc tem mais e mais prprio incluem-arquivos para manter, ser um pain to keep track of all include files and the files which are depending on it. dor de manter o controle de todos os arquivos de incluso e os arquivos que esto dependendo dela. If you change an include-file but forget Se voc alterar um arquivo-incluem, mas esquecer to recompile all the files which are depending on it, the results will be devastating. recompilar todos os arquivos que dependem disso, os resultados sero devastadores. gcc gcc has an option to analyze your tem uma opo para analisar o seu files and to produce a list of include-files and their dependencies: arquivos e para produzir uma lista de inclui-arquivos e suas dependncias: -MM -MM . . If you add this to your Makefile: Se voc adicionar isso ao seu Makefile: depend: dependem: gcc -E -MM *.c > .depend gcc-E-MM *. c>. depender and run *make depend* , the file e executar *make depend,* o arquivo .depend . Depender will appear with a list of object-files, C-files and the include-files: aparecer uma lista de arquivos-objeto, C-arquivos e os-arquivos incluem: foo.o: foo.c foo.h foo.o: foo.c foo.h If you change Se voc mudar foo.h foo.h , next time you run , Da prxima vez que voc executar make fazer all files depending on todos os arquivos dependendo foo.h foo.h will be recompiled. ser recompilado. Don't forget to run No se esquea de executar make depend fazer depender each time you add an include-file to one of your files. cada vez que voc adicionar uma include-file para um dos seus arquivos. *5.5.4.* *5.5.4.* *FreeBSD Makefiles* *FreeBSD Makefiles* Makefiles can be rather complicated to write. Makefiles pode ser um pouco complicado de escrever. Fortunately, BSD-based systems like FreeBSD come with some very Felizmente, os sistemas baseados em BSD como

FreeBSD vem com alguns muito powerful ones as part of the system. os poderosos, como parte do sistema. One very good example of this is the FreeBSD ports system. Um bom exemplo disso o sistema de ports FreeBSD. Here's the essential Aqui est o essencial part of a typical ports parte de um portos tpicos Makefile Makefile : : MASTER_SITES= MASTER_SITES = ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/ ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/ DISTFILES= DISTFILES = scheme-microcode+dist-7.3-freebsd.tgz esquema de microcdigo + dist-7.3-freebsd.tgz .include < bsd.port.mk > . Include Now, if we go to the directory for this port and type *make* , the following happens: Agora, se formos para o diretrio para esta porta e tipo de *make,* acontece o seguinte: 1. 1. A check is made to see if the source code for this port is already on the system. A verificao feita para ver se o cdigo-fonte para essa porta j est no sistema. 2. 2. If it isn't, an FTP connection to the URL in MASTER_SITES is set up to download the source. Caso no seja, uma conexo FTP para o URL em MASTER_SITES est configurado para baixar a fonte. /19/ /19/ -----------------------------------------------------------------------*Page 28* *Page 28* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ 3. 3. The checksum for the source is calculated and compared it with one for a known, good, copy of the source. A soma de verificao da fonte calculado e comparado com um para um conhecido, bom, cpia da fonte. This Este is to make sure that the source was not corrupted while in transit. ter a certeza de que a fonte no foi corrompido enquanto em trnsito. 4. 4. Any changes required to make the source work on FreeBSD are appliedthis is known as /patching/ . Quaisquer alteraes necessrias para tornar o trabalho a fonte em FreeBSD so aplicados, isto conhecido como /patching./ 5. 5. Any special configuration needed for the source is done. Nenhuma configurao especial necessria para que a fonte seja feito. (Many Unix program distributions try to work out (Muitas distribuies do programa Unix tentar descobrir which version of Unix they are being compiled on and which optional Unix features are presentthis is where qual verso do Unix esto sendo compilados e quais as caractersticas do Unix opcionais esto presentes, este o lugar onde they are given the information in the FreeBSD ports scenario). eles recebem a informao no cenrio portas FreeBSD). 6. 6. The source code for the program is compiled. O cdigo fonte para o programa compilado. In effect, we change to the directory where the source was Com efeito, podemos mudar para o diretrio onde a fonte era unpacked and do descompactado e fazer make fazer the program's own make file has the necessary information to build the program. -O prprio arquivo make do programa tem as informaes necessrias para a construo do programa. 7. 7. We now have a compiled version of the program. Temos agora uma verso compilada do programa. If we wish, we can test it now; when we feel confident about Se quisermos, podemos test-lo agora, quando se

sentir confiante sobre the program, we can type *make install* . o programa, podemos digitar *make install.* This will cause the program and any supporting files it needs to be Isso vai fazer com que o programa e os arquivos de suporte que ele precisa ser copied into the correct location; an entry is also made into a package database, so that the port can easily be copiado para a localizao correcta; uma entrada tambm feita numa base de dados de pacote, de modo que a porta pode ser facilmente uninstalled later if we change our mind about it. desinstalado mais tarde, se mudarmos de idia sobre isso. Now I think you'll agree that's rather impressive for a four line script! Agora eu acho que voc vai concordar que bastante impressionante para um script de linha de quatro! The secret lies in the last line, which tells O segredo est na ltima linha, que conta make fazer to look in the system makefile called olhar no makefile sistema chamado bsd.port.mk bsd.port.mk . . It's easy to fcil overlook this line, but this is where all the clever stuff comes fromsomeone has written a makefile that tells ignorar esta linha, mas este o lugar onde todas as coisas inteligente vem, algum escreveu um makefile que diz make fazer to do all the things above (plus a couple of other things I didn't mention, including handling any errors that may fazer todas as coisas acima (mais um par de outras coisas que eu no mencionei, incluindo manipulao quaisquer erros que possam occur) and anyone can get access to that just by putting a single line in their own make file! ocorrer) e qualquer pessoa pode ter acesso a que apenas colocando uma nica linha em seu prprio arquivo make! If you want to have a look at these system makefiles, they're in Se voc quiser ter um olhar para esses sistema makefiles, eles esto em /usr/share/mk / Usr / share / mk , but it's probably best to wait until , Mas provavelmente melhor esperar at que you've had a bit of practice with makefiles, as they are very complicated (and if you do look at them, make sure you voc teve um pouco de prtica com makefiles, como eles so muito complicadas (e se voc olhar para eles, certifique-se have a flask of strong coffee handy!) ter um frasco de caf forte calhar!) *5.5.5.* *5.5.5.* *More advanced uses of* *Usos mais avanados do* *make* *fazer* Make Fazer is a very powerful tool, and can do much more than the simple example above shows. uma ferramenta muito poderosa, e pode fazer muito mais do que o simples exemplo acima mostra. Unfortunately, there are Infelizmente, existem several different versions of vrias verses diferentes de make fazer , and they all differ considerably. , E todos eles diferem consideravelmente. The best way to learn what they can do is A melhor maneira de saber o que eles podem fazer probably to read the documentationhopefully this introduction will have given you a base from which you can do provavelmente para ler a documentao do esperanosamente esta introduo ter dado uma base a partir da qual voc pode fazer this. isto. The version of make that comes with FreeBSD is the *Berkeley make* ;

there is a tutorial for it in A verso da marca que vem com o FreeBSD o *Berkeley fazer,* h um tutorial para ele em /usr/share/doc/psd/12.make / Usr/share/doc/psd/12.make . . To view it, do Para v-lo, faz% % *zmore paper.ascii.gz* *zmore paper.ascii.gz* in that directory. nesse diretrio. /20/ /20/ -----------------------------------------------------------------------*Page 29* *Page 29* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ Many applications in the ports use *GNU make* , which has a very good set of info pages. Muitas aplicaes nas portas de usar *o GNU make,* que tem um bom conjunto de "Info" pginas. If you have installed any Se voc tiver instalado qualquer of these ports, *GNU make* will automatically have been installed as destas portas, *GNU make* ser automaticamente ter sido instalado como gmake gmake . . It's also available as a port and package Tambm est disponvel como um porto e um pacote in its own right. em seu prprio direito. To view the info pages for *GNU make* , you will have to edit the Para visualizar as pginas de informao para *GNU make,* voc ter que editar o dir dir file in the arquivo no /usr/local/info / Usr / local / info directory to add diretrio para adicionar an entry for it. uma entrada para ele. This involves adding a line like Isso envolve a adio de uma linha como * Make: (make). * Marca: (fazer). The GNU Make utility. O GNU Make utilidade. to the file. para o arquivo. Once you have done this, you can type *info* and then select make from the menu (or in *Emacs* , do *Ch* Depois de ter feito isso, voc pode digitar *informaes* e, em seguida, escolha fazer a partir do menu (ou no *Emacs,* fazer *Ch* *i* ). *i).* *5.6.* *5.6.* *Debugging* *Depurao* *5.6.1.* *5.6.1.* *The Debugger* *O Debugger* The debugger that comes with FreeBSD is called O depurador que vem com o FreeBSD chamado gdb gdb ( *GNU debugger* ). *(Depurador GNU).* You start it up by typing Voc inici-lo digitando % % *gdb /progname/* *gdb /nomeprog/* although most people prefer to run it inside *Emacs* . embora a maioria das pessoas preferem execut-lo dentro *do Emacs.* You can do this by: Voc pode fazer isso: *Mx gdb RET /progname/ RET* *Mx gdb /nomeprog/ RET RET* Using a debugger allows you to run the program under more controlled circumstances. Usando um depurador permite que voc execute o programa em circunstncias mais controladas. Typically, you can step Normalmente, voc pode entrar through the program a line at a time, inspect the value of variables, change them, tell the debugger to run up to a atravs do programa de uma linha de cada vez, inspecionar o valor de variveis, alter-los, dizer que o depurador para correr at a certain point and then stop, and so on. certo ponto e depois parar, e assim por diante. You can even attach to a program that's already

running, or load a core file to Voc pode at mesmo anexar a um programa que j est em execuo, ou carregar um arquivo de ncleo para investigate why the program crashed. investigar por que o programa travou. It's even possible to debug the kernel, though that's a little trickier than the user ainda possvel depurar o kernel, no entanto, que um pouco mais complicado do que o usurio applications we'll be discussing in this section. aplicaes vamos discutir nesta seo. gdb gdb has quite good on-line help, as well as a set of info pages, so this section will concentrate on a few of the basic tem muito bom de ajuda on-line, bem como um conjunto de pginas de informaes, por isso esta seo ir concentrar-se em alguns dos bsicos commands. comandos. Finally, if you find its text-based command-prompt style off-putting, there's a graphical front-end for it xxgdb Finalmente, se voc encontrar o seu estilo baseado em texto de prompt de comando off-putting, h um front-end grfico para ele xxgdb (../../ports/devel.html) in the ports collection. (.. /.. / Ports / devel.html) na coleo de ports. This section is intended to be an introduction to using Esta seco pretende ser uma introduo ao uso gdb gdb and does not cover specialised topics such as debugging e no cobre assuntos especializados, tais como a depurao the kernel. o kernel. /21/ /21/ -----------------------------------------------------------------------*Page 30* *Page 30* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ *5.6.2.* *5.6.2.* *Running a program in the debugger* *Executando um programa no depurador* You'll need to have compiled the program with the Voc precisa ter compilado o programa com a -g -G option to get the most out of using opo para tirar o mximo proveito do uso de gdb gdb . . It will work without, Ele vai trabalhar fora, but you'll only see the name of the function you're in, instead of the source code. mas voc s vai ver o nome da funo que voc est dentro, em vez de o cdigo fonte. If you see a line like: Se voc ver uma linha como: ... ... (no debugging symbols found) ... (Sem smbolos de depurao encontrado) ... when quando gdb gdb starts up, you'll know that the program wasn't compiled with the inicia-se, voc vai saber que o programa no foi compilado com o -g -G option. opo. At the No gdb gdb prompt, type *break main* . prompt, digite *quebrar principal.* This will tell the debugger to skip over the preliminary set-up code in the Isto ir dizer o depurador para pular o cdigo set-up preliminar no program and start at the beginning of your code. programa e comear no incio do seu cdigo. Now type *run* to start the programit will start at the beginning of Agora digite *correr* para iniciar o programa, ele

vai comear no incio do the set-up code and then get stopped by the debugger when it calls o cdigo de set-up e, em seguida, ficar parado pelo depurador quando ele chama main() main () . . (If you've ever wondered where (Se voc j se perguntou onde main() main () gets called from, now you know!). chamado de, agora voc sabe!). You can now step through the program, a line at a time, by pressing Agora voc pode percorrer o programa, uma linha de cada vez, pressionando n n . . If you get to a function call, you can step into Se voc chegar a uma chamada de funo, voc pode entrar em it by pressing lo premindo s s . . Once you're in a function call, you can return from stepping into a function call by pressing Uma vez que voc estiver em uma chamada de funo, voc pode retornar de pisar em uma chamada de funo, premindo f f . . You Voc can also use Tambm possvel utilizar up para cima and e down para baixo to take a quick look at the caller. para dar uma olhada rpida no interlocutor. Here's a simple example of how to spot a mistake in a program with Aqui est um exemplo simples de como identificar um erro em um programa com gdb gdb . . This is our program (with a deliberate Este o nosso programa (com a deliberada mistake): erro): #include < stdio.h > # Include int bazz(int anint); int bazz (int anInt); main() { main () { int i; int i; printf("This is my program\n"); printf ("Este o meu programa \ n"); bazz(i); bazz (i); return 0; retornar 0; } } int bazz(int anint) { int bazz (int anInt) { printf("You gave me %d\n", anint); printf ("Voc me deu% d \ n", anInt); return anint; voltar anInt; } } This program sets i to be Este programa define i ser 5 5 and passes it to a function e passa para uma funo bazz() bazz () which prints out the number we gave it. que imprime o nmero que deu. When we compile and run the program we get Quando compilar e executar o programa de chegarmos % % *cc -g -o temp temp.c* *cc-g-o temp temp.c* % % *./temp* *. / Temp* This is my program Este o meu programa anint = 4231 anInt = 4231 /22/ /22/ -----------------------------------------------------------------------*Page 31* *Page 31*

/Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ That wasn't what we expected! Isso no era o que espervamos! Time to see what's going on! Tempo para ver o que est acontecendo! % % *gdb temp* *gdb temperatura* GDB is free software and you are welcome to distribute copies of it GDB um software livre e voc est convidado a distribuir cpias do mesmo under certain conditions; type "show copying" to see the conditions. sob certas condies, tipo "show copiar" para ver as condies. There is absolutely no warranty for GDB; type "show warranty" for details. No h absolutamente nenhuma garantia para o GDB, tipo "show de garantia" para obter detalhes. GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc. GDB 4.13 (i386-unknown-freebsd) Copyright 1994 Free Software Foundation, Inc. (gdb) *break main* /Skip the set-up code/ (Gdb) *break principal* /Skip o cdigo set-up/ Breakpoint 1 at 0x160f: file temp.c, line 9. Breakpoint 1 em 0x160f: file temp.c, linha 9. /gdb/ /gdb/ /puts breakpoint at/ /coloca ponto de interrupo na/ /main()/ /main ()/ (gdb) *run* /Run as far as/ (Gdb) /*Run* Run, tanto quanto/ /main()/ /main ()/ Starting program: /home/james/tmp/temp /Program starts running/ Programa de partida: / home / james / tmp / /Programa de/ temperatura /comea a funcionar/ Breakpoint 1, main () at temp.c:9 Breakpoint 1 main () em temp.c: 9 /gdb/ /gdb/ /stops at/ /paradas em/ /main()/ /main ()/ (gdb) *n* /Go to next line/ (Gdb) *n* /Ir para a prxima linha/ This is my program /Program prints out/ Este o meu /programa/ programa /imprime/ (gdb) *s* /step into/ (Gdb) *s* /passo para/ /bazz()/ /bazz ()/ bazz (anint=4231) at temp.c:17 bazz (anInt = 4,231) no temp.c: 17 /gdb/ /gdb/ /displays stack frame/ /apresenta quadro de pilha/ (gdb) (Gdb) Hang on a minute! Espere um minuto! How did anint get to be Como anInt chegar a ser 4231 4231 ? ? Didn't we set it to be No podemos defini-lo para ser 5 5 in em main() main () ? ? Let's move up to Vamos passar para main() main () and e have a look. dar uma olhada. (gdb) *up* /Move up call stack/ (Gdb) *para cima* /Mover para cima pilha de chamadas/ #1 0x1625 in main () at temp.c:11 1 0x1625 em main () em temp.c: 11 /gdb/ /gdb/ /displays stack frame/ /apresenta quadro de pilha/ (gdb) *pi* /Show us the value of i/ (Gdb) *pi* /Mostra-nos o valor de i/ $1 = 4231 $ 1 = 4231 /gdb/ /gdb/

/displays/ /monitores/ /4231/ /4231/ Oh dear! Oh dear! Looking at the code, we forgot to initialise i. Olhando para o cdigo, que se esqueceu de inicializar i. We meant to put Quisemos colocar /.../ /.../ main() { main () { int i; int i; i = 5; i = 5; printf("This is my program\n"); printf ("Este o meu programa \ n"); /.../ /.../ but we left the mas deixamos a i=5; i = 5; line out. sada de linha. As we didn't initialise i, it had whatever number happened to be in that area of memory Como no inicializar i, que tinha o nmero que passou a ser na rea de memria when the program ran, which in this case happened to be quando o programa executado, o qual, neste caso, por acaso 4231 4231 . . /23/ /23/ -----------------------------------------------------------------------*Page 32* *Page 32* /Chapter 5./ /Captulo 5./ /Programming Tools/ /Ferramentas de Programao/ *Note:* *Nota:* gdb gdb displays the stack frame every time we go into or out of a function, even if we're using mostra o quadro de pilha cada vez que vamos para dentro ou fora de uma funo, mesmo se estiver usando up para cima and e down para baixo to a move around the call stack. mover a pilha de chamadas. This shows the name of the function and the values of its arguments, which helps us Isso mostra o nome da funo e os valores de seus argumentos, o que nos ajuda a keep track of where we are and what's going on. manter o controle de onde estamos eo que est acontecendo. (The stack is a storage area where the program stores (A pilha uma rea de armazenamento, onde o programa armazena information about the arguments passed to functions and where to go when it returns from a function call). informaes sobre os argumentos passados para as funes e para onde ir, quando ele retorna de uma chamada de funo). *5.6.3.* *5.6.3.* *Examining a core file* *Examinando um arquivo de ncleo* A core file is basically a file which contains the complete state of the process when it crashed. Um arquivo de ncleo basicamente um arquivo que contm o estado completo do processo quando ele caiu. In the good old Em "o


Recommended