• Aucun résultat trouvé

U IX" System V/386

N/A
N/A
Protected

Academic year: 2022

Partager "U IX" System V/386 "

Copied!
556
0
0

Texte intégral

(1)

U IX" System V/386

Release 3.2

I

\tbl I

~

G)

~ ~ I l m

(fj

G)

C o

m

a:

c::: z

>< •

f ~

85 en

PREHT1CE HALl.

(2)

••

AllaY

UNIX® System V/386 Release 3.2

Programmer's Guide, Vol. I

(3)

Library of Congress Catalog Card Number: 88-62526

Editorial/production supervision: Karen Skrable Fortgang Manufacturing buyer: Mary Ann Gloriande

C> 1989 by AT&T. Allrigb"",,,,,><d.

~ Published by Prentice-Hall, Inc.

=-

A Division of Simon & Schuster Englewood Cliffs, New Jersey 07632

All rights reserved. Nopartof this book maybe reproduced, in any form or by any means, without permission in writing from the publisher.

NOTICE

The information in this document is subject to change without notice.

AT&T assumes no responsibility for any errors that may appear in this document.

DEC, PDP, VAX, and VT100 are trademarks of Digital Equipment Corporation.

DOCUMENTER'S WORKBENCH is a registered trademark of AT&T.

Intel is a registered trademark of Intel Corporation.

TELETYPE is a registered trademark of AT&T.

UNIX is a registered trademark of AT&T.

WRITER'S WORKBENCH is a registered trademark of AT&T.

The publisher offers discounts on this book when ordered in bulk quantities. For more information, write or call:

Special Sales Prentice-Hall, Inc.

College Technical and Reference Division Englewood Cliffs, NJ 07632

(201) 592-2498

Printed in the United States of America 10 9 8 7 6 5 4 3 2 I

ISBN

0-13-944877-2

Prentice-Hall International (UK) limited, London Prentice-Hall of AustraliaPty.limited, Sydney Prentice-Hall Canada Inc., Toronto

Prentice-Hall Hispanoamericana. S.A .• Mexico Prentice-Hall of India Private limited. New De/hi Prentice-Hall of Japan, Inc., Tokyo

Simon & Schuster AsiaPte.Ud., Singapore Editora Prentice-Hall do Brasil. Uda.• Rio de Janeiro

(4)

Table of Contents

Volume I

Introduction

1

2

3

Introduction

Programming in A UNIX System Environment: An Overview

Introduction

UNIX System Tools and Where You Can Read About Them

Three Programming Environments Summary

Programming Basics

Introduction

Choosing a Programming Language After Your Code Is Written

The Interface Between a Programming Language and the UNIX System

AnalysisjDebugging

Program Organizing Utilities

Application Programming

Introduction

Application Programming

xxv

1-1 1-4 1-7 1-9

2-1 2-2 2-7 2-11 2-43 2-66

3-1 3-2

(5)

Table of Contents - - - -

4

5

6

Language Selection

Advanced Programming Tools Programming Support Tools Project Control Tools liber, A Ubrary System

awk

Introduction Basic awk Patterns Actions Output Input

Using awk with Other Commands and the Shell Example Applications

awk Summary

lex

An Overview of lex Programming Writing lex Programs

Running lex under the UNIX System

yacc

Introduction Basic Specifications Parser Operation

Ambiguity and Conflicts Precedence

Error Handling

The yacc Environment

Hintsfor Preparing Specifications Advanced Topics

Examples

3-5 3-13 3-21 3-34 3-38

4-1 4-2 4-12 4-20 4-38 4-43 4-49 4-52 4-58

5-1 5-3 5-18

6-1 6-4 6-13 6-18 6-24 6-28 6-32 6-34 6-38 6-45

iv PROGRAMMER'S GUIDE

(6)

7

8

File and Record Locking

Introduction Terminology File Protection

Selecting Advisory or Mandatory Locking

Shared Libraries

Introduction

Using a Shared Library Building a Shared Library Summary

Table of Contents

7-1 7-2 7-4 7-18

8-1 8-2 8-15 8-59

9 Interprocess Communication

Introduction Messages Semaphores Shared Memory

9-1 9-2 9-38 9-75

Glossary

Glossary G-1

Index

Index 1-1

Volume II

1 0 Extended Terminal Interface

Overview 10-1

What is ETI? 10-5

Basic ETI Programming 10-9

(7)

Table of Contents

Simple Input and Output Windows

Panels

Compiling and Linking Panel Programs Creating Panels

Elementary Panel Window Operations

Moving Panels to the Top or Bottom of the Deck Updating Panels on the Screen

Making Panels Invisible

Fetching Panels Above or Below Given Panels Setting and Fetching the Panel User Pointer Deleting Panels

Menus

Compiling and linking Menu Programs Overview: Writing Menu Programs in ETI Creating and Freeing Menu Items

Two Kinds of Menus: Single- and Multi-Valued Manipulating Item Attributes

Setting the Item User Pointer Creating and Freeing Menus Manipulating Menu Attributes Displaying Menus

Menu Driver Processing

Manipulating the Menu User Pointer Setting and Fetching Menu Options Forms

Compiling and Linking Form Programs Overview: Writing Form Programs in ETI Creating and Freeing Fields

Manipulating Field Attributes

Setting the Field Foreground, Background, and Pad Character

Some Helpful Features of Fields Manipulating Field Options Creating and Freeing Forms Manipulating Form Attributes Displaying Forms

Form Driver Processing

vi PROGRAMMER'S GUIDE

10-18 10-58 10-69 10-70 10-71 10-72 10-75 10-76 10-78 10-80 10-82 10-85 10-86 10-87 10-88 10-92 10-95 10-97 10-102 10-105 10-108 10-112 10-130 10-153 10-156 10-160 10-161 10-162 10-169 10-173 10-185 10-187 10-195 10-199 10-203 10-206 10-214

(8)

Table of Contents

11

12

13

Setting and Fetching the Form User Pointer Setting and Fetching Form Options

Creating and Manipulating Programmer-Defined Field Types

Other ETI Routines

Routines for Drawing lines and Other Graphics Routines for Using Soft Labels

Working with More than One Terminal Working with terminfo Routines Working with the terminfo Database TAM Transition library

Compiling and Running TAM Applications under ETI Tips for Polishing TAM Application Programs

Running under ETI

How the TAM Transition library Works Program Examples

Common Object File Format (coH)

The Common Object File Format (COFF)

The Link Editor

The Link Editor

link Editor Command Language Notes and Special Considerations Syntax Diagram for Input Directives

make

Introduction Basic Features

Description Files and Substitutions Recursive Makefiles

Source Code Control System File Names: the Tilde Command Usage

Suggestions and Warnings Internal Rules

10-241 10-243 10-246 10-259 10-260 10-262 10-264 10-266 10-272 10-284 10-285 10-286 10-287 10-296

11-1

12-1 12-4 12-22 12-32

13-1 13-2 13-7 13-11 13-17 13-21 13-24 13-25

(9)

Table of Contents

14

15

16

17

Source Code Control System (sees)

Introduction

SCCS For Beginners Delta Numbering

SCCS Command Conventions SCCS Commands

SCCS Files

sdb-the Symbolic Debugger

Introduction Using sdb

lint

Introduction Usage

lint Message Types

C Language

Introduction

Lexical Conventions Storage Class and Type Operator Conversions Expressions and Operators Declarations

Statements

External Definitions Scope Rules

Compiler Control Lines Types Revisited

Constant Expressions Portability Considerations Syntax Summary

14-1 14-2 14-7 14-10 14-12 14-37

15-1 15-2

16-1 16-2 16-4

17-1 17-2 17-6 17-9 17-12 17-23 17-37 17-43 17-45 17-47 17-52 17-57 17-58 17-59

viii PROGRAMMER'S GUIDE

(10)

- - - Table of Contents

18

A

C Programmer's Productivity Tools

Introducing the C Programmer's Productivity Tools cscope

lprof

Profiling Examples

Index to Utilities

Appendix A: Index to Utilities

18-1 18-3 18-29 18-47

A-1

Glossary

Glossary G-1

Index

Index 1-1

(11)
(12)

List of Figures

Figure 2·1: Using Command line Arguments to Set Flags 2-13 Figure 2·2: Using argv[n) Pointers to Pass a File Name 2-14 Figure 2·3: C Language Standard I/O Subroutines 2-17

Figure 2-4: String Operations 2-19

Figure 2·5: Classifying ASCII Character-Coded Integer Values 2-19 Figure 2-6: Conversion Functions and Macros 2-20

Figure 2·7: Manual Page for gets(3S) 2-23

Figure 2·8: How gets Is Used in a Program 2-24 Figure 2-9: A Version of stdio.h (Sheet 1 of 2) 2-25 Figure 2-9: A Version of stdio.h (Sheet 2 of 2) 2-26 Figure 2·10: Environment and Status System Calls 2-33

Figure 2·11: Process Status 2-34

Figure 2-12: Example of fork 2-37

Figure 2-13: Example of a popen pipe 2-39

Figure 2·14: Signal Numbers Defined in

/usr/include/sys/signal.h 2-41

Figure 2·15: Source Code for Sample Program (Sheet 1 of 4) 2-44 Figure 2·15: Source Code for Sample Program (Sheet 2 of 4) 2-45

(13)

List of Figures

Figure 2-15: Source Code for Sample Program (Sheet 3 of 4) 2-46 Figure 2-15: Source Code for Sample Program (Sheet 4 of 4) 2-47

Figure 2-16: cflow Output, No Options 2-48

Figure 2-17: cflow Output, Using r Option 2-49 Figure 2-18: cflow Output, Using ix Option 2-50 Figure 2-19: cflow Output, Using rand ix Options 2-51 Figure 2-20: ctrace Output (Sheet 1 of 3) 2-53 Figure 2-20: ctrace Output (Sheet 2 of 3) 2-54 Figure 2-20: ctrace Output (Sheet 3 of 3) 2-55 Figure 2-21: cxref Output, Using c Option (Sheet 1 of 5) 2-56 Figure 2-21: cxref Output, Using c Option (Sheet 2 of 5) 2-57 Figure 2-21: cxref Output, Using c Option (Sheet 3 of 5) 2-58 Figure 2-21: cxref Output, Using c Option (Sheet 4 of 5) 2-59 Figure 2-21: cxref Output, Using c Option (Sheet 5 of 5) 2-60

Figure 2-22: lint Output 2-61

Figure 2-23: prof Output 2-64

Figure 2-24: make Description File 2-67

Figure 2-25: nm Output, with f Option (Sheet 1 of 5) 2-70 Figure 2-25: nm Output, with f Option (Sheet 2 of 5) 2-71 Figure 2-25: nm Output, with f Option (Sheet 3 of 5) 2-72 Figure 2-25: nm Output, with f Option (Sheet 4 of 5) 2-73 Figure 2-25: nm Output, with f Option (Sheet 5 of 5) 2-74

xII PROGRAMMER'S GUIDE

(14)

List of Figures

Figure 3-1: Thefcntl.h Header File 3-16

Figure 3-2: Object File Ubrary Functions (Sheet 1 Of 2) 3-25 Figure 3-2: Object File Ubrary Functions (Sheet 2 Of 2) 3-26 Figure 4-1: awkProgram Structure and Example 4-2 Figure 4-2: The Sample Input Filecountries 4-4

Figure 4-3: awk Comparison Operators 4-14

Figure 4-4: awkRegular Expressions 4-18

Figure 4-5: awk Built-in Variables 4-20

Figure 4-6: awk Built-in Arithmetic Functions 4-23 Figure 4-7: awkBuilt-in String Functions 4-24 Figure 4-8: awk printfConversion Characters 4-39

Figure 4-9: getline Function 4-47

Figure 5-1: Creation and Use of a Lexical Analyzer with lex 5-2 Figure 8-1: a.out Files Created Using an Archive Library and a

Shared Library 8-8

Figure 8-2: Processes Using an Archive and a Shared Ubrary 8-9 Figure 8-3: A Branch Table in a Shared Ubrary 8-12 Figure 8-4: Imported SYmbols in a Shared Ubrary 8-32

Figure 8-5: File10g.c 8-50

Figure 8-6: Filepoly.c 8-51

Figure 8-7: Filestats.c 8-52

Figure 8-8: Header Filemaux.h 8-53

Figure 8-9: Specification File 8-56

(15)

List of Figures

Figure 9-1: ipc-perm Data Structure 9-5

Figure 9-2: Operation Permissions Codes 9-8

Figure 9-3: Control Commands (Flags) 9-9

Figure 9-4: msggetO System Call Example (Sheet 1 of 3) 9-13 Figure 9-4: msggetO System Call Example (Sheet 2 of 3) 9-14 Figure 9-4: msggetO System Call Example (Sheet 3 of 3) 9-15 Figure 9-5: msgctlO System Call Example (Sheet 1 of 4) 9-20 Figure 9-5: msgctlO System Call Example (Sheet 2 of 4) 9-21 Figure 9-5: msgctlO System Call Example (Sheet 3 of 4) 9-22 Figure 9·5: msgctlO System Call Example (Sheet 4 of 4) 9-23 Figure 9·6: msgopO System Call Example (Sheet 1 of 7) 9-31 Figure 9·6: msgopO System Call Example (Sheet 2 of 7) 9-32 Figure 9·6: msgopO System Call Example (Sheet 3 of 7) 9-33 Figure 9-6: msgopO System Call Example (Sheet 4 of 7) 9-34 Figure 9-6: msgopO System Call Example (Sheet 5 of 7) 9-35 Figure 9-6: msgopO System Call Example (Sheet 6 of 7) 9-36 Figure 9-6: msgopO System Call Example (Sheet 7 of 7) 9-37

Figure 9·7: Operation Permissions Codes 9-46

Figure 9-8: Control Commands (Flags) 9-46

Figure 9-9: semget() System Call Example (Sheet 1 of 3) 9-50 Figure 9-9: semgetO System Call Example (Sheet 2 of 3) 9-51 Figure 9-9: semgetO System Call Example (Sheet 3 of 3) 9-52

xlv PROGRAMMER'S GUIDE

(16)

List of Figures

Figure 9-10: semctlOSystem Call Example (Sheet 1 of7) 9-60 Figure 9-10: semctlOSystem Call Example (Sheet 2 of 7) 9-61 Figure 9-10: semctlOSystem Call Example (Sheet 3 of 7) 9-62 Figure 9-10: semctlOSystem Call Example (Sheet 4 of 7) 9-63 Figure 9-10: semctlOSystem Call Example (Sheet 5 of 7) 9-64 Figure 9-10: semctlOSystem Call Example (Sheet 6 of 7) 9-65 Figure 9-10: semctlO System Call Example (Sheet 7 of 7) 9-66 Figure 9-11: semop(2) System Call Example (Sheet 1 of 4) 9-71 Figure 9-11: semop(2)System Call Example (Sheet 2 of 4) 9-72 Figure 9-11: semop(2) System Call Example (Sheet 3 of 4) 9-73 Figure 9-11: semop(2) System Call Example (Sheet 4 of 4) 9-74 Figure 9-12: Shared Memory State Information 9-78 Figure 9-13: Operation Permissions Codes 9-82

Figure 9-14: Control Commands (Flags) 9-82

Figure 9-15: shmget(2) System Call Example (Sheet 1 of 3) 9-86 Figure 9-15: shmget(2) System Call Example (Sheet 2 of 3) 9-87 Figure 9-15: shmget(2) System Call Example (Sheet 3 of 3) 9-88 Figure 9-16: shmctl(2)System Call Example (Sheet 1 of 6) 9-93 Figure 9-16: shmctl(2) System Call Example (Sheet 2 of 6) 9-94 Figure 9-16: shmctl(2) System Call Example (Sheet 3 of 6) 9-95 Figure 9-16: shmctl(2)System Call Example (Sheet 4 of 6) 9-96 Figure 9-16: shmctlO System Call Example (Sheet 5 of 6) 9-97

(17)

List of Figures

Figure 9-16: shmctl(2) System Call Example (Sheet 6 of 6) 9-98 Figure 9-17: shmopO System Call Example (Sheet 1 of 4) 9-103 Figure 9-17: shmopO System Call Example (Sheet 2 of 4) 9-104 Figure 9-17: shmopO System Call Example (Sheet 3 of 4) 9-105 Figure 9-17: shmopO System Call Example (Sheet 4 of 4) 9-106

Figure 10-1: A Simple ETI Program 10-6

Figure 10-2: The Purposes of initscrO, refreshO, and endwinO

in a Program 10-11

Figure 10-3: The Relationship between stdscr and a Terminal

Screen 10-15

Figure 10-3: The Relationship Between stdscr and a Terminal

Screen (continued) 10-16

Figure 10-4: Multiple Windows and Pads Mapped to a Physical

Screen 10-17

Figure 10-5: Input Option Settings for ETI Programs 10-54 Figure 10-6: Using wnoutrefreshO and doupdateO 10-60 Figure 10-7: The Relationship Between a Window and a Termi-

nal Screen 10-61

Figure 10-7: The Relationship Between a Window and a Termi-

nal Screen (continued) 10-62

Figure 10-7: The Relationship Between a Window and a Termi-

nal Screen (continued) 10-63

Figure 10-8: Sample Routines for Low-Level ETI (curses) Inter-

face 10-67

Figure 10-9: Example Using Panel User Pointer 10-83

Figure 10-10: A Sample Menu 10-86

xvi PROGRAMMER'S GUIDE

(18)

List of Figures

Figure 10·11 = Sample Menu Program to Create a Menu in ETI 10-90 Figure 10-12: Creating an Array of Items 10-93 Figure 10-13= Using itellL.valueO in Menu Processing 10-96 Figure 10-14: Using an Item User Pointer 10-103 Figure 10·15= Changing the Items Associated With a Menu 10-109 Figure 10·16= Examples of Menu Format (2, 2) 10-114 Figure 10-17= Examples of Menu Format (3, 2) 10-115 Figure 10-18= Examples of Menu Format (4, 3) 10-115 Figure 10·19= Menu Functions Write to Subwindow, Application

to Window 10-121

Figure 10-20: Creating a Menu with a Border 10-122 Figure 10·21= Sample Routines Displaying and Erasing Menus 10-128 Figure 10-22= Sample Routine that Translates Keys into Menu

Requests 10-132

Figure 10·23= Integer Ranges for ETI Key Values and MENU

Requests 10-136

Figure 10·24: Sample Menu Output (2) 10-137 Figure 10-25= Sample Program Calling the Menu Driver 10-140 Figure 10-28= Using an Initialization Routine to Generate Item

Prompts 10-145

Figure 10-27= Returning Cursor to its Correct Position for Menu

Driver Processing 10-150

Figure 10·28= Example Setting and Using A Menu User Pointer 10-154

Figure 10·29= Sample Form Display 10-160

(19)

List of Figures

Figure 10-30: Code To Produce a Simple Form

Figure 10-31: Example Shifting All Form Fields a Given Number of Rows

Figure 10-32: Setting a Field to TYPE-ENUM of Colors Figure 10-33: Using the Field Status to Update a Database Figure 10-34: Using the Field User Pointer to Match Items Figure 10-35: Creating a Form

Figure 10·36: Form Functions Write to Subwindow, Application to Window

Figure 10-37: Creating a Border Around a Form Figure 10·38: Posting and Unposting a Form Figure 10·39: ASample Key Virtualization Routine Figure 10-40: Sweepstakes Form Output

Figure 10·41: An Example of Form Driver Usage

Figure 10-42: Sample Termination Routine that Updates a Column Total

Figure 10·43: Field Initialization and Termination to Highlight Current Field

Figure 10·44: Example Manipulating the Current Field

Figure 10·45: Example Changing and Checking the Form Page Number

Figure 10-46: Repositioning the Cursor After Printing Page Number

Figure 10-47: Pattern Match Example Using form User Pointer Figure 10·48: Creating a Programmer-Defined Field Type

xviii PROGRAMMER'S GUIDE

10-165

10-175 10-180 10-190 10-193 10-201

10-209 10-210 10-212 10-217 10-224 10-228

10-233

10-234 10-236

10-238

10-239 10-242 10-249

(20)

Ust of Figures

Figure 10-49: Creating TYPEJiEX with Padding and Range Arguments

Figure 10-50: Creating a Next Choice Function for a Field Type Figure 10-51: Sending a Message to Several Terminals

Figure 10-52: Typical Framework of a terminfo Program Figure 10-53: Translations from TAM to ETI Function Calls

(Sheet 1 of 4)

Figure 10-53: Translations from TAM to ETI Function Calls (Sheet 2 of 4)

Figure 10-53: Translations from TAM to ETI Function Calls (Sheet 3 of 4)

Figure 10-53: Translations from TAM to ETI Function Calls (Sheet 4 of 4)

Figure 10-54: TAM High-Level Functions

Figure 10-55: Translation Between TAM Escape Sequences and Virtual Key Values

Figure 11-1: Object File Format Figure 11·2: File Header Contents Figure 11·3: File Header Flags Figure 11-4: File Header Declaration Figure 11-5: Optional Header Contents Figure 11·6: UNIX System Magic Numbers Figure 11·7: aouthdrDeclaration

Figure 11·8: Section Header Contents Figure 11-9: Section Header Flags

10-254 10-257 10-265 10-267

10-287

10-288

10-289

10-289 10-291

10-294 11-2 11-4 11-5 11-6 11-7 11-8 11-9 11-10 11-11

(21)

List of Figures

Figure 11-10: Section Header Declaration 11-12 Figure 11-11: Relocation Section Contents 11-13

Figure 11-12: Relocation Types 11-14

Figure 11·13: Relocation Entry Declaration 11-15

Figure 11-14: line Number Grouping 11-16

Figure 11·15: line Number Entry Declaration 11-17

Figure 11-16: COFF Symbol Table 11-18

Figure 11-17: Special Symbols in the Symbol Table 11-19 Figure 11-18: Special Symbols (.bb and .eb) 11-20

Figure 11·19: Nested blocks 11-21

Figure 11-20: Example of the Symbol Table 11-22

Figure 11-21: Symbols for Functions 11-22

Figure 11-22: Symbol Table Entry Format 11-23

Figure 11-23: Name Field 11-24

Figure 11·24: Storage Classes 11-25

Figure 11-25: Storage Class by Special Symbols 11-26 Figure 11-26: Restricted Storage Classes 11-27 Figure 11-27: Storage Class and Value 11-28

Figure 11-28: Section Number 11-29

Figure 11-29: Section Number and Storage Class 11-30

Figure 11-30: Fundamental Types 11-31

Figure 11-31: Derived Types 11-32

xx PROGRAMMER'S GUIDE

(22)

List of Figures

Figure 11-32: Type Entries by Storage Class 11-33 Figure 11-33: Symbol Table Entry Declaration 11-35 Figure 11-34: Auxiliary Symbol Table Entries 11-36 Figure 11-35: Format for Auxiliary Table Entries for Sections 11-37

Figure 11-36: Tag Names Table Entries 11-38

Figure 11-37: Table Entries for End of Structures 11-38 Figure 11-38: Table Entries for Functions 11-39

Figure 11-39: Table Entries for Arrays 11-39

Figure 11-40: End of Block and Function Entries 11-40 Figure 11-41: Format for Beginning of Block and Function 11-40 Figure 11-42: Entries for Structures, Unions, and Enumerations 11-41 Figure 11-43: Auxiliary Symbol Table Entry (Sheet 1 of 2) 11-42 Figure 11-43: Auxiliary Symbol Table Entry (Sheet 2 of 2) 11-43

Figure 11-44: String Table 11-44

Figure 12-1: Operator Symbols 12-5

Figure 12-2: Syntax Diagram for Input Directives (Sheet 1 of 4) 12-32 Figure 12-2: Syntax Diagram for Input Directives (Sheet 2 of 4) 12-33 Figure 12·2: Syntax Diagram for Input Directives (Sheet 3 of 4) 12-34 Figure 12·2: Syntax Diagram for Input Directives (Sheet 4 of 4) 12-35 Figure 13·1: Summary of Default Transformation Path 13-13 Figure 13-2: make Internal Rules (Sheet 1 of 5) 13-25 Figure 13-2: make Internal Rules (Sheet 2 of 5) 13-26

(23)

List of Figures

Figure 13·2: make Internal Rules (Sheet 3 of 5) 13-27 Figure 13·2: make Internal Rules (Sheet 4 of 5) 13-28 Figure 13-2: make Internal Rules (Sheet 5 of 5) 13-29

Figure 14·1: Evolution of an SCCS File 14-7

Figure 14-2: Tree Structure with Branch Deltas 14-8

Figure 14-3: Extended Branching Concept 14-9

Figure 14-4: Determination of New SID 14-21

Figure 15-1: Example of sdb Usage (Sheet 1 of 3) 15-13 Figure 15-1: Example of sdb Usage (Sheet 2 of 3) 15-14 Figure 15-1: Example of sdb Usage (Sheet 3 of 3) 15-15 Figure 17-1: Escape Sequences for Nongraphic Characters 17-4 Figure 17-2: Computer Hardware Characteristics 17-7

Figure 18-1: The cscope Menu of Tasks 18-6

Figure 18-2: Menu Manipulation Commands 18-7

Figure 18-3: Requesting a Search for a Text String 18-8 Figure 18-4: cscope Lists Lines Containing the Text String 18-9 Figure 18-5: Commands for Use After Initial Search 18-10 Figure 18-6: Examining a Line of Code Foundbycscope 18-11 Figure 18-7: Requesting a List of Functions that Call alloctest 18-12 Figure 18-8: cscope Lists Functions that Call alloctest 18-13 Figure 18-9: cscope Lists Functions that Call mymalloc 18-14 Figure 18-10: Viewing dispinitin the Editor 18-15

xxii PROGRAMMER'S GUIDE

(24)

List of Figures

Figure 18-11: Using cscope to Fix the Problem 18-16 Figure 18-12: Commands for Selecting Lines to be Changed 18-20

Figure 18-13: Changing a Text String 18-21

Figure 18-14: cscope Prompts for Unes to be Changed 18-22 Figure 18-15: Marking Lines to be Changed 18-23 Figure 18-16: cscope Displays Changed Lines of Text 18-24 Figure 18-17: Escaping from escape to the Shell 18-25

Figure 18-18: Example of Iprof Output 18-37

Figure 18-19: Example of Output Produced by the x Option 18-39 Figure 18·20: Example of Iprof s Output 18-41

Figure 18·21: prof Output 18-48

Figure 18·22: Iprof Output for the Function CAfind 18-50 Figure 18·23: Iprof Output for New Version of Function CAfind 18-54 Figure 18·24: prof Output for New Version of Iprof 18-56 Figure 18·25: Iprof Summary Output for a Test Suite 18-57 Figure 18-26: Fragment of Output from Iprof x 18-59 Figure 18·27: Output from Iprof x for Function putdata 18-60

(25)
(26)

Introduction

Purpose

This guide is designed to give you information about programming in the UNIX System V/386 operating system environment. Itdoes not attempt to teach you how to write programs. Rather, it is intended to supplement texts on programming languages by concentrating on the other elements that are part of getting programs into operation.

Audience and Prerequisite Knowledge

As the title suggests, we are addressing programmers, especially those who have not worked extensively with the UNIX System. No special level of programming involvement is assumed. We hope the book will be useful to people who write only an occasional program, as well as to those who work on or manage large application development projects.

Programmers in the expert class, or those engaged in developing system software, may find this guide lacks the depth of information they need. For them we recommend theProgrammer's Reference Manual.

Knowledge of terminal use, of a UNIX System editor, and of the UNIX System directory/file structure is assumed. Ifyou feel shaky about your mastery of these basic. tools, you might want to look over theUser's Guide before tackling this one. The material is organized into eighteen chapters.

The C Connection

The UNIX System supports many programming languages, and C com- pilers are available on many different operating systems. Nevertheless, the relationship between the UNIX Operating System and C has always been and remains very close. Most of the code in the UNIX Operating System is C, and over the years many organizations using the UNIX System have come to use C for an increasing portion of their application code. Thus, while this guide is intended to be useful to you no matter what language(s) you are using, you will find that, unless there is a specific language-dependent point to be made, the examples assume you are programming in C.

(27)

Introduction

Hardware/Software Dependencies

The text reflects the way things work on your computer running UNIX System V/386 at the Release 3.2 level. Ifyou find commands that work a lit- tle differently in your UNIX System environment, it may be because you are running under a different release of the software. Ifsome commands do not seem to exist at all, they may be members of packages not installed on your system. Appendix A describes the command packages available on your com- puter. Ifyou do find yourself trying to execute a non-existent command, check Appendix A, then talk to the administrators of your system.

Notational Conventions

Whenever the text includes examples of output from the computer and/or commands entered by you, we follow the standard notation scheme that is common throughout UNIX System documentation:

• Commands, options, arguments to commands, and directory and file names that you type in from your terminal are shown in boldtype.

• Text that is printed on your terminal by the computer is shown in constant widthtype. Constant width type is also used for code sam- ples because it allows the most accurate representation of spacing.

Spacing is often a matter of coding style but is sometimes critical.

• Comments added to a display to show that part of the display has been omitted are shown in italictype and are indented to separate them from the text that represents computer output or input. Com- ments that explain the input or output are shown in the same type font as the rest of the display.

Italics are also used to show substitutable values, such as, filename, when the format of a command is shown.

• There is an implied RETURN at the end of each command and menu response you enter. Where you may be expected to enter only a RETURN (as in the case where you are accepting a menu default), the symbol <CR> is used.

xxvi PROGRAMMER'S GUIDE

(28)

Introduction

• In cases where you are expected to enter a control character, it is shown as, for example, CTRL-D. This means that you press the d key on your keyboard while holding down the CTRL key.

• The dollar sign($) and pound sign(#) are the standard default prompt signs for an ordinary user and root. $ means you are logged in as an ordinary user. # means you are logged in as root.

• When the # prompt is used in an example, it means the command illustrated may be used only by root.

Command References

When commands are mentioned in a section of the text for the first time, a reference to the manual section where the command is formally described is included in parentheses, that is, command(section). Numbered sections are located in the following manuals:

Sections (1, 1M), (7) User'sjSystem Administrator's Reference Manual Sections(1), (2), (3), (4), (5) Programmer's Reference Manual

Information in the Examples

While every effort has been made to present displays of information just as they appear on your terminal, it is possible that your system may produce slightly different output. Some displays depend on a particular machine con- figuration that may differ from yours. Changes between releases of the UNIX System software may cause small differences in what appears on your termi- nal.

Where complete code samples are shown, we have tried to make sure they compile and work as represented. Where code fragments are shown, while we cannot say that they have been compiled, we have attempted to maintain the same standards of coding accuracy for them.

(29)
(30)

1 Programming in A UNIX System Environment: An Overview

Introduction

1-1

The Early Days 1-1

UNIX System Philosophy Simply Stated 1-3

UNIX System Tools and Where

You Can Read About Them

1-4 Tools Covered and Not Covered in this Guide 1-4

The Shell as a Prototyping Tool 1-5

Three Programming Environments

1-7

Single-User Programmer 1-7

Application Programming 1-8

Systems Programmers 1-8

Summary

1-9

(31)

~.-_.~~.-.~!~

(32)

Introduction

The 1983 Turing Award of the Association for Computing Machinery was given jointly to Ken Thompson and Dennis Ritchie, the two men who first designed and developed the UNIX Operating System. The award citation said, in part:

The success of the UNIX System stems from its tasteful selec- tion of a few key ideas and their elegant implementation. The model of the UNIX System has led a generation of software designers to new ways of thinking about programming. The genius of the UNIX System is its framework which enables programmers to stand on the work of others.

As programmers working in a UNIX System environment, why should we care what Thompson and Ritchie did? Does it have any relevance for us today?

Itdoes because if we understand the thinking behind the system design and the atmosphere in which it flowered, it can help us become productive UNIX System programmers more quickly.

The Early Days

You may already have read about how Ken Thompson came across a DEC PDP-7 machine sitting unused in a hallway at AT&T Bell Laboratories, and how he and Dennis Ritchie and a few of their colleagues used that as the ori- ginal machine for developing a new operating system that became UNIX.

The important thing to realize, however, is that what they were trying to do was fashion a pleasant computing environment for themselves. Itwas not,

IILet's get together and build an operating system that will attract world-wide attention. "

The sequence in which elements of the system fell into place is interest- ing. The first piece was the file system, followed quickly by its organization into a hierarchy of directories and files. The view of everything, data stores, programs, commands, directories, even devices, as files of one type or another was critical, as was the idea of a file as a one-dimensional array of bytes with no other structure implied. The cleanness and simplicity of this way of look- ing at files has been a major contributing factor to a computer environment that programmers and other users have found comfortable.

(33)

Introduction

The next element was the idea of processes, with one process being able to create another and communicate with it. This innovative way of looking at running programs as processes led easily to the practice (quintessentially UNIX System) of reusing code by calling it from another process. With the addition of commands to manipulate fIles and an assembler to produce exe- cutable programs, the system was essentially able to function on its own.

The next major development was the acquisition of a DEC PDP-II and the installation of the new system on it. This has been described by Ritchie as a stroke of good luck, in that the PDP-II was to become a hugely successful machine, its success to some extent adding momentum to the acceptance of the system that began to be known by the name of UNIX System.

By 1972 the innovative idea of pipes (connecting links between processes whereby the output of one becomes the input of the next) had been incor- porated into the system, the operating system had been recoded in higher level languages (first B, then C) and had been dubbed with the name UNIX System (coined by Brian Kernighan). By this point, the "pleasant computing environmentII sought by Thompson and Ritchie was a reality; but some other things were going on that had a strong influence on the character of the pro- duct then and today.

Itis worth pointing out that the UNIX System came out of an atmosphere that was totally different from that in which most commercially successful operating systems are produced. The more typical atmosphere is that

described by Tracy Kidder inThe Soul of a New Machine. In that case, dozens of talented programmers worked at white heat, in an atmosphere of extremely tight security, against murderous deadlines. By contrast, the UNIX System could be said to have had about a ten-year gestation period. From the begin- ning it attracted the interest of a growing number of brilliant specialists, many of whom found in the UNIX System an environment that allowed them to pursue research and development interests of their own, but who, in tum., contributed additions to the body of tools available for succeeding ranks of UNIX System programmers.

Beginning in 1971, the system began to be used for applications within AT&T Bell Laboratories, and shortly thereafter (1974) was made available at low cost and without support to colleges and universities. These versions, called research versions and identifted with Arabic numbers up through 7, occasionally grew on their own and fed back to the main system additional innovative tools. The widely-used screen editor vi(I), for example, was added to the UNIX System by William joy at the University of California, Berkeley.

In 1979, acceding to commercial demand, AT&T began offering supported

1-2 PROGRAMMER'S GUIDE

(34)

Introduction versions (called development versions) of the UNIX System. These are identi- fied with Roman numerals and often have interim release numbers appended.

The current development version, for example, is UNIX System V/386 Release 3.2.

Versions of the UNIX System being offered now are coming from an environment more closely related, perhaps, to the standard software factory.

Features are being added to new releases in response to the expressed needs of the market place. The essential quality of the UNIX System, however, remains as the product of the innovative thinking of its originators and the collegial atmosphere in which they worked. This quality has on occasion been referred to as the UNIX System philosophy, but what is meant is the way in which sophisticated programmers have come to work with the UNIX System.

UNIX System Philosophy Simply Stated

For as long as you are writing programs on a UNIX System you should keep this motto hanging on your wall:

* * * * * * * * * * * * * * * * * * * * *

*

*

*

Build em the work of others

*

* *

* * * * * * * * * * * * * * * * * * * * *

Unlike computer environments where each new project is like starting with a blank canvas, on a UNIX System a good percentage of any program- ming effort is lying there in bins, andtbins,and /usr/bins,not to mention etc, waiting to be used.

The features of the UNIX System (pipes, processes, and the flie system) contribute to this reusability, as does the history of sharing and contributing that extends back to 1969. You risk missing the essential nature of the UNIX Systemifyou do not put this to work.

(35)

UNIX System Tools and Where You Can Read About Them

The term "UNIX System toolsII can stand some clarification. In the nar- rowest sense, it means an existing piece of software used as a component in a new task. In a broader context, the term is often used to refer to elements of the UNIX System that might also be called features, utilities, programs, filters, commands, languages, functions, and so on. Itgets confusing because any of the things that might be called by one or more of these names can be, and often are, used in the narrow way as part of· the solution to a programming problem.

Tools Covered and Not Covered in this Guide

TheProgrammer's Guideis about tools used in the process of creating pro- grams in a UNIX System environment, so let us take a minute to talk about which tools we mean, which ones are not going to be covered in this book, and where you might find information about those not covered here. Actu- ally, the subject of things not covered in this guide might be even more important to you than the things that are. We could not possibly cover every- thing you ever need to know about UNIX System tools in this one volume.

Tools not covered in this text:

• theloginprocedure

• UNIX System editors and how to use them

• how the file system is organized and how you move around init

• shell programming

Information about these subjects can be found in the User's Guide and a number of commercially available texts.

Tools covered here can be classified as follows:

• utilities for getting programs running

• utilities for organizing software development projects

• specialized languages

1-4 PROGRAMMER'S GUIDE

(36)

UNIX System Tools

• debugging and analyzing tools

• compiled language components that are not part of the language syn- tax, for example, standard libraries, systems calls, and functions

The Shell as a Prototyping Tool

Any time you log in to a UNIX System machine you are using the shell.

The shell is the interactive command interpreter that stands between you and the UNIX System kernel, but that is only part of the story. Because of its abil- ity to start processes, direct the flow of control, field interrupts, and redirect input and output,itis a full-fledged programming language. Programs that use these capabilities are known as shell procedures or shell scripts.

Much innovative use of the shell involves stringing together commands to be run under the control of a shell script. The dozens and dozens of com- mands that can be used in this way are documented in theUser'sjSystem Administrator's Reference Manual. Time spent with the User'sjSystem

Administrator's Reference Manual can be rewarding. Look throughitwhen you are trying to find a command with just the right option to handle a knotty programming problem. The more familiar you become with the commands described in the manual pages, the more you will be able to take full advan- tage of the UNIX System environment.

Itis not our purpose here to instruct you in shell programming. What we want to stress here is the important part that shell procedures can play in developing prototypes of full-scale applications. While understanding all the nuances of shell programming can be a fairly complex task, getting a shell procedure up and running is far less time-consuming than writing, compiling, and debugging compiled code.

This ability to get a program into production quickly is what makes the shell a valuable tool for program development. Shell programming allows you to "build on the work of others" to the greatest possible degree, since it allows you to piece together major components simply and efficiently. Many times even large applications can be done using shell procedures. Even if the application is initially developed as a prototype system for testing purposes rather than being put into production, many months of work can be saved.

(37)

UNIX System Tools

With a prototype for testing, the range of possible user errors can be determined-something that is not always easy to plan out when an applica- tion is being designed. The method of dealing with strange user input can be worked out inexpensively, avoiding large re-coding problems.

A common occurrence in the UNIX System environment is to find that an available UNIX System tool can accomplish with a couple of lines of instruc- tions what might take a page and a half of compiled code. Shell procedures can intermix compiled modules and regular UNIX System commands to let you take advantage of work that has gone before.

1-6 PROGRAMMER'S GUIDE

(38)

Three Programming Environments

We distinguish among three programming environments to emphasize that the information needs and the way in which UNIX System tools are used differ from one environment to another. We do not intend to imply a hierar- chy of skill or experience. Highly-skilled programmers with years of experi- ence can be found in the "single-user" category, and relative newcomers can be members of an application development or systems programming team.

Single-User Programmer

Programmers in this environment are writing programs only to ease the performance of their primary job. The resulting programs might well be added to the stock of programs available to the community in which the pro- grammer works. This is similar to the atmosphere in which the UNIX System thrived; someone develops a useful tool and shares it with the rest of the organization. Single-user programmers may not have externally imposed requirements, or co-authors, or project management concerns. The program- ming task itself drives the coding very directly. One advantage of a timeshar- ing system such as UNIX System is that people with programming skills can be set free to work on their own without having to go through formal project approval channels and perhaps wait for months for a programming depart- ment to solve their problems.

Single-user programmers need to know how to do the following:

• select an appropriate language

• compile and run programs

• use system libraries

• analyze programs

• debug programs

• keep track of program versions

Most of the information to perform these functions at the single-user level can be found in Chapter 2.

(39)

Three Programming Environments

Application Programming

Programmers working in this environment are developing systems for the benefit of other, non-programming users. Most large commercial computer applications still involve a team of applications development programmers.

They may be employees of the end-user organization, or they may work for a software development firm. Some of the people working in this environment may be more in the project management area than working programmers.

Information needs of people in this environment include all the topics in Chapter 2, plus additional information on the following:

• software control systems

• file and record locking

• communication between processes

• shared memory

• advanced debugging techniques These topics are discussed in Chapter 3.

Systems Programmers

These are programmers engaged in writing software tools that are part of, or closely related to, the operating system itself. The project may involve writing a new device driver, a database management system, or an enhance- ment to the UNIX System kernel. In addition to knowing their way around the operating system source code and how to make changes and enhance- ments to it, they need to be thoroughly familiar with all the topics covered in Chapters 2 and 3.

1·8 PROGRAMMER'S GUIDE

(40)

Summary

In this overview chapter we have described the way that the UNIX Sys- tem developed and the effect that has on the way programmers now work with it. We have described what is and is not to be found in the other chapters of this guide to help programmers. We have also suggested that in many cases programming problems may be easily solved by taking advantage of the UNIX System interactive command interpreter known as the shell.

Finally, we identified three programming environments, in the hope that it will help orient the reader to the organization of the text in the remaining chapters.

(41)
(42)

2 Programming Basics

Introduction

2-1

Choosing a Programming

Language

2-2

Supported Languages in a UNIX System

Environment 2-2

• C Language 2-3

• Assembly Language 2-4

Special Purpose Languages 2-4

.~k ~

• lex 2-5

• yacc 2-5

• m4 2-6

• be and de 2-6

• curses 2-6

After Your Code Is Written

2-7

Compiling and Link Editing 2-8

• Compiling C Programs 2-8

• Compiler Diagnostic Messages 2-9

• Link Editing 2-9

The Interface Between a

Programming Language and the

UNIX System

2-11

Why C Is Used to Illustrate the Interface 2-11

(43)

Programming Basics

How Arguments Are Passed to a Program 2-12

System Calls and Subroutines 2-15

• Categories of System Calls and Subroutines 2-15

• Where the Manual Pages Can Be Found 2-21

• How System Calls and Subroutines Are Used in

C Programs 2-21

Header Files and Libraries 2-27

Object File Libraries 2-28

Input/Output 2-29

• Three Files You Always Have 2-29

• Named Files 2-30

• Low-Level I/O and Why You Should Not UseIt 2-32 System Calls for Environment or Status Information 2-32

Processes 2-33

• system(3S) 2-35

• exec(2) 2-35

• fork(2) 2-36

• Pipes 2-38

Error Handling 2-40

Signals and Interrupts 2-40

Analysis/Debugging

2-43

Sample Program 2-43

cflow 2-48

ctrace 2-51

cxref 2-55

lint 2-61

prof 2-62

size 2-64

strip 2-64

sdb 2-64

Program Organizing Utilities

2-66

The make Command 2-66

The Archive 2-68

Use of SCCSbySingle-User Programmers 2-74

(44)

Introduction

The information in this chapter is for anyone just learning to write pro- grams to run in a UNIX System environment. In Chapter 1 we identified one group of UNIX System users as single-user programmers. People in that category, particularly those who are not deeply interested in programming, may find that this chapter (plus related reference manuals) tells them as much as they need to know about coding and running programs on a UNIX System computer.

Programmers whose interest does run deeper, who are part of an applica- tion development project, or who are producing programs on one UNIX Sys- tem computer that are being ported to another, should view this chapter as a

starter package.

(45)

Choosing a Programming Language

How do you decide which programming language to use in a given situa- tion? One answer could be, "I always code inHAIRBOL, because that's the language I know best." Actually, in some circumstances that is a legitimate answer. But, assuming more than one programming language is available to you, that different programming languages have their strengths and

weaknesses, and assuming that once you have learned to use one program- ming language it becomes relatively easy to learn to use another, you might approach the problem of language selection by asking yourself questions like the following:

• What is the nature of the task this program is to do?

Does the task call for the development of a complex algorithm, or is this a simple procedure that has to be done on a lot of records?

• Does the programming task have many separate parts?

Can the program be subdivided into separately compilable functions, or is it one module?

• How soon does the program have to be available?

Is it needed right now, or do I have enough time to work out the most efficient process possible?

• What is the scope of its use?

Am I the only person who will use this program, or is it going to be distributed to the whole world?

• Is there a possibility the programwillbe ported to other systems?

• What is the life expectancy of the program?

Is it going to be used just a few times, or will it still be going strong five years from now?

Supported Languages in a UNIX System Environment

By IIsupported languages" we mean those offered by AT&T for use on your computer running UNIX System V/386 Release 3.2. Since these are separately purchasable items, not all of them will necessarily be installed on

2·2 PROGRAMMER'S GUIDE

(46)

Language Selection your machine. On the other hand, you may have languages available on your machine that came from another source and are not mentioned in this discus- sion. Be that as it may, in this section and the one to follow we give brief descriptions of the nature of (a) the C programming language, and (b) a number of special purpose languages.

C Language

The C language is intimately associated with the UNIX System, sinceit was originally developed for use in recoding the UNIX System kernel. Ifyou need to use a lot of UNIX System function calls for low-level I/O, memory or device management, or inter-process communication, C language is a logical first choice. Most programs, however, do not require such direct interfaces with the operating system, so the decision to choose C might better be based on one or more of the following characteristics:

• a variety of data types: character, integer, long integer, float, and double

• low-level constructs (most of the UNIX System kernel is written in C)

• derived data types such as arrays, functions, pointers, structures, and unions

• multi-dimensional arrays

• scaled pointers and the ability to do pointer arithmetic

• bit-wise operators

• a variety of flow-of-control statements: if, if-else, switch, while, do- while, and for

• a high degree of portability

C is a language that lends itself readily to structured programming. Itis natural in C to think in terms of functions. The next logical step is to view each function as a separately compilable unit. This approach (coding a pro- gram in small pieces) eases the job of making changes and/or improvements.

Ifthis begins to sound like the UNIX System philosophy of building new pro- grams from existing tools, it is not just coincidence. As you create functions for one program, you will surely find that many can be picked up or quickly revised for another program.

(47)

Language Selection

A difficulty with C is that it takes a fairly concentrated use of the language over a period of several months to reach your full potential as a C program- mer. Ifyou are a casual programmer, you might make life easier for yourself ifyou choose a less demanding language.

Assembly Language

The closest approach to machine language, assembly language is specific to the particular computer on which your program is to run. High-level languages are translated into the assembly language for a specific processor as one step of the compilation. The most common need to work in assembly language arises when you want to do some task that is not within the scope of a high-level language. Since assembly language is machine-specific, pro- grams written in it are not portable.

Special Purpose Languages

In addition to the above formal programming languages, the UNIX System environment frequently offers one or more of the special purpose languages listed below.

Since UNIX System utilities and commands are packaged in functional groupings,itis possible that not all the facilities mentionedwillbe available on all systems.

awk

awk (its name is an acronym constructed from the initials of its develop- ers) scans an input file for lines that match pattern(s) described in a specifica- tion file. On finding a line that matches a pattern, awk performs actions also described in the specification. Itis not uncommon that an awk program can be written in a couple of lines to do functions that would take a couple of pages to describe in a programming language like FORTRAN or C. For exam- ple, consider a case where you have a set of records that consist of a key field and a second field that represents a quantity. You have sorted the records by the key field, and you now want to add the quantities for records with dupli- cate keys and output a file in which no keys are duplicated.

2-4 PROGRAMMER'S GUIDE

(48)

Language Selection The pseudo-code for such a program might look like this:

Read the first record into a hold area;

Read additional records until EOF;

{

Ifthe key matches the key of the record in the hold area, add the quantity to the quantity field of the held record;

Ifthe key does not match the key of the held record, write the held record,

move the new record to the hold area;

}

At EOF, write out the last record from the hold area.

An awk program to accomplish this task would look like this:

{ ~[$1] += $2 }

END { far (key in qty) print key, qty[key] }

This illustrates only one characteristic of awk; its ability to work with associa- tive arrays. With awk, the input file does not have to be sorted, which is a requirement of the pseudo-program.

lex

lex is a lexical analyzer that can be added to C programs. A lexical analyzer is interested in the vocabulary of a language rather than its grammar, which is a system of rules defining the structure of a language. lex can pro- duce C language subroutines that recognize regular expressions specified by the user, take some action when a regular expression is recognized, and pass the output stream on to the next program.

yacc

yacc (Yet Another Compiler Compiler) is a tool for describing an input language to a computer program. yacc produces a C language subroutine that parses an input stream according to rules laid down in a specification file.

The yacc specification fIle establishes a set of grammar rules together with actions to be taken when tokens in the input match the rules. lex may be used with yacc to control the input process and pass tokens to the parser that applies the grammar rules.

(49)

Language Selection

m4

m4 is a macro processor that can be used as a preprocessor for assembly language and C programs. It is described in Section (1) of the Programmer's Reference Manual.

be and de

be enables you to use a computer terminal as you would a programmable calculator. You can edit a file of mathematical computations and call be to execute them. The be program uses de. You can use de directlyifyou want, but it takes a little getting used to since it works with reverse Polish notation.

That means you enter numbers into a stack followed by the operator. be and de are described in Section (1) of the User's/System Administrator's Reference Manual.

curses

Actually a library of C functions, curses is included in this list because the set of functions just about amounts to a sub-language for dealing with termi- nal screens. Ifyou are writing programs that include interactive user screens, you will want to become familiar with this group of functions.

In addition to all the foregoing, do not overlook the possibility of using shell procedures.

2-& PROGRAMMER'S GUIDE

(50)

After Your Code Is Written

The last two steps in most compilation systems in the UNIX System environment are the assembler and the link editor. The compilation system produces assembly language code. The assembler translates that code into the machine language of the computer the program is to run on. The link editor resolves all undefined references and makes the object module executable.

With most languages on the UNIX System the assembler and link editor pro- duce files in what is known as the Common Object File Format (COFF). A common format makes it easier for utilities that depend on information in the object file to work on different machines running different versions of the UNIX System.

In the Common Object File Format an object file contains the following:

• a file header

• optional secondary header

• a table of section headers

• data corresponding to the section header(s)

• relocation information

• line numbers

• a symbol table

• a string table

An object file is made up of sections. Usually, there are at least two:

.text,and .data. Some object files contain a section called.bss. (.bssis an assembly language pseudo-op that originally stood for IIblock started by sym- bol. n) Options of the compilers cause different items of information to be includedinthe Common Object File Format. For example, compiling a program with the -goption adds line numbers and other symbolic informa- tion that is needed for the sdb (Symbolic Debugger) command to be fully effective. You can spend many years programming without having to worry too much about the contents and organization of the Common Object File Format, so we are not going into any further depth of detail at this point.

Detailed information is available in Chapter 11 of this guide.

(51)

Compiling and Link Editing

Compiling and Link Editing

The command used for compiling depends on the language used; for C programs, cc both compiles and link edits.

Compiling C Programs

To use the C compilation system you must have your source code in a file with a file name that ends in the characters .c, as in mycode.c. The command to invoke the compiler is

cc mycode.c

Ifthe compilation is successful, the process proceeds through the link edit stage, and the result will be an executable file by the name of a.out.

Several options to the cc command are available to control its operation.

The most used options are:

-c causes the compilation system to suppress the link edit phase. This produces an object file (mycode.o) that can be link edited at a later time with a cc command without the -c option.

-g causes the compilation system to generate special informa- tion about variables and language statements used by the symbolic debugger sdb. Ifyou are going through the stage of debugging your program, use this option.

-0 causes the inclusion of an additional optimization phase.

This option is logically incompatible with the -g option.

You would normally use -0 after the program has been debugged, to reduce the size of the object file and increase execution speed.

-p causes the compilation system to produce code that works in conjunction with the prof(I) command to produce a runtime profile of where the program is spending its time.

See the Programmer's Reference Manual for the prof(I) manual page. This is usefulin identifying which routines are candidates for improved code.

2·8 PROGRAMMER'S GUIDE

(52)

-ooutfile

Compiling and Link Editing tells ee to tell the link editor to use the specified name for the executable file, rather than the default a.out.

Other options can be used with ee. Check theProgrammer's Reference Manual.

Ifyou enter the ee command using a file name that ends in.5, the compi- lation system treats it as assembly language source code and bypasses all the steps ahead of the assembly step.

Compiler Diagnostic Messages

The C compiler generates error messages for statements that do not com- pile. The messages are generally quite understandable, but in common with most language compilers they sometimes point several statements beyond where the actual error occurred. For example,ifyou inadvertently put an extra; at the end of an if statement, a subsequent else will be flagged as a sYntax error. In the case where a block of several statements follows the if, the line number of the syntax error caused by the else will start you looking for the error well past where it is. Unbalanced curly braces, { }, are another common producer of syntax errors.

Link Editing

The ld command invokes the link editor directly. The typical user, how- ever, seldom invokes ld directly. A more common practice is to use a

language compilation control command (such as ee) that invokes ld. The link editor combines several object files into one, performs relocation, resolves external symbols, incorporates startup routines, and supports symbol table information used by sdb. You may, of course, start with a single object file rather than several. The resulting executable module is left in a file named a.out.

Any file named on the ld command line that is not an object file (typi- cally, a name ending in 0) is assumed to be an archive library or a file of link editor directives. The ld command has some 16 options. We are going to describe four of them. These options should be fed to the link editor by speci- fYing them on the ee command line if you are doing both jobs with the single command, which is the usual case.

-0outfile provides a name to be used to replace a.out as the name of the output file. Obviously, the name a.out is of only tem- porary usefulness. Ifyou know the name you want to use to invoke your program, you can provide it here. Of

Références

Documents relatifs

This procedure allows the calculation of multiplier effects induced by changes in final demand for all goods both in quantities and in prices, a distinct and

The following function prints its string argument followed by a newline character to std_err and then flushes

In this paper, we describe a semantics for a lazy language based on Haskell, supporting monadic I/O, mutable variables, usual recursive definitions, and value recursion.. Our

Separators extend the operations allowed for contractors to non monotonic

The proposed approach is based on the characterization of the class of initial state vectors and control input signals that make the outputs of different continuous

The Data Read is delayed from Data Write and may be shifted into an external register by using the negative-going edge of the Data Read Shift Clocks or the

With a parallel printer port, three serial ports (one standard and two optional), and a game port, the Magic I/O packs more features and connectors on a true

Ecrit un byte, en fait un int pour qu'il marche avec le read. void write(int b) Ne