Hands On: C Programming and Unix Application Design: UNIX System Calls and Subroutines Using C

Total Page:16

File Type:pdf, Size:1020Kb

Hands On: C Programming and Unix Application Design: UNIX System Calls and Subroutines Using C Hands On: C Programming and Unix Application Design: UNIX System Calls and Subroutines using C c A. D. Marshall 1998-2004 ii Contents 1 C/C++ Program Compilation 1 1.1 Creating, Compiling and Running Your Program . 1 1.1.1 Creating the program . 1 1.1.2 Compilation . 2 1.1.3 Running the program . 3 1.2 The C Compilation Model . 3 1.2.1 The Preprocessor . 3 1.2.2 C Compiler . 5 1.2.3 Assembler . 5 1.2.4 Link Editor . 5 1.2.5 Some Useful Compiler Options . 5 1.2.6 Using Libraries . 6 1.2.7 UNIX Library Functions . 7 1.2.8 Finding Information about Library Functions . 7 1.3 Lint | A C program verifier . 8 1.4 Exercises . 9 2 C Basics 11 2.1 History of C . 11 2.2 Characteristics of C . 12 2.3 C Program Structure . 14 2.4 Variables . 16 2.4.1 Defining Global Variables . 17 2.4.2 Printing Out and Inputting Variables . 19 2.5 Constants . 19 2.6 Arithmetic Operations . 20 2.7 Comparison Operators . 21 2.8 Logical Operators . 22 iii iv CONTENTS 2.9 Order of Precedence . 22 2.10 Exercises . 24 3 Conditionals 27 3.1 The if statement . 27 3.2 The ? operator . 28 3.3 The switch statement . 29 3.4 Exercises . 31 4 Looping and Iteration 33 4.1 The for statement . 33 4.2 The while statement . 34 4.3 The do-while statement . 36 4.4 break and continue ....................... 37 4.5 Exercises . 37 5 Arrays and Strings 43 5.1 Single and Multi-dimensional Arrays . 43 5.2 Strings . 44 5.3 Exercises . 45 6 Functions 47 6.1 void functions . 48 6.2 Functions and Arrays . 48 6.3 Function Prototyping . 49 6.4 Exercises . 51 7 Further Data Types 57 7.1 Structures . 57 7.1.1 Defining New Data Types . 58 7.2 Unions . 59 7.3 Coercion or Type-Casting . 61 7.4 Enumerated Types . 62 7.5 Static Variables . 63 7.6 Exercises . 64 8 Pointers 65 8.1 What is a Pointer? . 65 8.2 Pointer and Functions . 69 CONTENTS v 8.3 Pointers and Arrays . 71 8.4 Arrays of Pointers . 73 8.5 Multidimensional arrays and pointers . 74 8.6 Static Initialisation of Pointer Arrays . 77 8.7 Pointers and Structures . 77 8.8 Common Pointer Pitfalls . 78 8.8.1 Not assigning a pointer to memory address before using it 78 8.8.2 Illegal indirection . 79 8.9 Exercise . 80 9 Dynamic Memory Allocation and Dynamic Structures 81 9.1 Malloc, Sizeof, and Free . 81 9.2 Calloc and Realloc . 83 9.3 Linked Lists . 84 9.4 Full Program: queue.c ...................... 84 9.5 Exercises . 88 10 Advanced Pointer Topics 91 10.1 Pointers to Pointers . 91 10.2 Command line input . 93 10.3 Pointers to a Function . 94 10.4 Exercises . 96 11 Low Level Operators and Bit Fields 99 11.1 Bitwise Operators . 99 11.2 Bit Fields . 101 11.2.1 Bit Fields: Practical Example . 102 11.2.2 A note of caution: Portability . 104 11.3 Exercises . 104 12 The C Preprocessor 107 12.1 #define . 108 12.2 #undef . 109 12.3 #include . 109 12.4 #if | Conditional inclusion . 109 12.5 Preprocessor Compiler Control . 110 12.6 Other Preprocessor Commands . 111 12.7 Exercises . 112 vi CONTENTS 13 C, UNIX and Standard Libraries 113 13.1 Advantages of using UNIX with C . 113 13.2 Using UNIX System Calls and Library Functions . 114 14 Integer Functions, Random Number, String Conversion, Search- ing and Sorting: <stdlib.h> 117 14.1 Arithmetic Functions . 117 14.2 Random Numbers . 119 14.3 String Conversion . 121 14.4 Searching and Sorting . 122 14.5 Exercises . 123 15 Mathematics: <math.h> 125 15.1 Math Functions . 125 15.2 Math Constants . 126 16 Input and Output (I/O):stdio.h 129 16.1 Reporting Errors . 129 16.1.1 perror() .........................129 16.1.2 errno . 130 16.1.3 exit() . 130 16.2 Streams . 130 16.2.1 Predefined Streams . 131 16.3 Basic I/O . 132 16.4 Formatted I/O . 133 16.4.1 Printf . 133 16.5 scanf . 135 16.6 Files . 135 16.6.1 Reading and writing files . 136 16.7 sprintf and sscanf . 137 16.7.1 Stream Status Enquiries . 138 16.8 Low Level I/O . 138 16.9 Exercises . 140 17 String Handling: <string.h> 143 17.1 Basic String Handling Functions . 143 17.1.1 String Searching . 145 17.2 Character conversions and testing: ctype.h . 147 CONTENTS vii 17.3 Memory Operations: <memory.h> . 148 17.4 Exercises . 148 18 File Access and Directory System Calls 151 18.1 Directory handling functions: <unistd.h> . 151 18.1.1 Scanning and Sorting Directories:<sys/types.h>,<sys/dir.h>152 18.2 File Manipulation Routines: unistd.h, sys/types.h, sys/stat.h . 155 18.2.1 File Access . 155 18.2.2 File Status . 156 18.2.3 File Manipulation:stdio.h, unistd.h . 157 18.2.4 Creating Temporary FIles:<stdio.h> . 158 18.3 Exercises . 158 19 Time Functions 161 19.1 Basic time functions . 161 19.2 Example time applications . 162 19.2.1 Example 1: Time (in seconds) to perform some com- putation . 163 19.2.2 Example 2: Set a random number seed . 163 19.3 Exercises . 164 20 Process Control: <stdlib.h>,<unistd.h> 165 20.1 Running UNIX Commands from C . 165 20.2 execl() . 166 20.3 fork() . 167 20.4 wait() . 168 20.5 exit() . ..
Recommended publications
  • Intermedia: a System for Linking Multimedia Documents. IRIS
    DOCUMENT RESUME ED 296 735 IR 052 399 AUTHOR Yankelovich, Nicole TITLE Intermedia: A System for Linking Multimrdia Documents. IRIS Technical Report 86-2. INSTITUTION Brown Univ., Providence, RI. Inst. for Research in Information and Scholarship. PUB DATE 86 NOTE 19p. PUB TYPE Reports - Descriptive (141) EDRS PRICE MF01/PC01 Plus Postage. D'1CRIPTORS Bibliographic Coupling; *Computer Assisted Instruction; Computer Graphics; *Computer System Design; Higher Education; *Information Retrieval; *Man Machine Systems; *Multimedia Instruction; Word Processing IDENTIFIERS *Hypermedia ABSTRACT "Intermedia" is a hypermedia system which was developed for use in university research and teaching. It provides a framework for object-oriented, direct manipulation editors and applications, and the capability to link together materials created with those applications. Instructors are able to construct exploratory environments for their students as well as use applications for their day-to-day work, research, and writing. This paper provides a discussion of hypermedia systems in general, as well as a description of the Intermedia system which focuses on several important user features, and illustrates the operation of the system thrw,h a sample session. The text is supplemented by 15 figures. (19 references) (Author/EW) *********************************************************************** Reproductions supplied by EDRS are the best that can be made from the original document. *********************************************************************** INTERMEDIA: A System for customizing, visualizing, integratingand 0 Linking Multimedia Documents retrieving information. oi This paper describes Intermedia,one such tool designed for use in theuniversity O Nicole Yankelovich environment. The system, developedat Lid "PERMISSION TO REPRODUCE THIS Brown University's Institute for Researchin MATERIAL HAS BEEN GRANTED BY Information and Scholarship (IRIS),contains U.S.
    [Show full text]
  • DC Console Using DC Console Application Design Software
    DC Console Using DC Console Application Design Software DC Console is easy-to-use, application design software developed specifically to work in conjunction with AML’s DC Suite. Create. Distribute. Collect. Every LDX10 handheld computer comes with DC Suite, which includes seven (7) pre-developed applications for common data collection tasks. Now LDX10 users can use DC Console to modify these applications, or create their own from scratch. AML 800.648.4452 Made in USA www.amltd.com Introduction This document briefly covers how to use DC Console and the features and settings. Be sure to read this document in its entirety before attempting to use AML’s DC Console with a DC Suite compatible device. What is the difference between an “App” and a “Suite”? “Apps” are single applications running on the device used to collect and store data. In most cases, multiple apps would be utilized to handle various operations. For example, the ‘Item_Quantity’ app is one of the most widely used apps and the most direct means to take a basic inventory count, it produces a data file showing what items are in stock, the relative quantities, and requires minimal input from the mobile worker(s). Other operations will require additional input, for example, if you also need to know the specific location for each item in inventory, the ‘Item_Lot_Quantity’ app would be a better fit. Apps can be used in a variety of ways and provide the LDX10 the flexibility to handle virtually any data collection operation. “Suite” files are simply collections of individual apps. Suite files allow you to easily manage and edit multiple apps from within a single ‘store-house’ file and provide an effortless means for device deployment.
    [Show full text]
  • Mipspro C++ Programmer's Guide
    MIPSproTM C++ Programmer’s Guide 007–0704–150 CONTRIBUTORS Rewritten in 2002 by Jean Wilson with engineering support from John Wilkinson and editing support from Susan Wilkening. COPYRIGHT Copyright © 1995, 1999, 2002 - 2003 Silicon Graphics, Inc. All rights reserved; provided portions may be copyright in third parties, as indicated elsewhere herein. No permission is granted to copy, distribute, or create derivative works from the contents of this electronic documentation in any manner, in whole or in part, without the prior written permission of Silicon Graphics, Inc. LIMITED RIGHTS LEGEND The electronic (software) version of this document was developed at private expense; if acquired under an agreement with the USA government or any contractor thereto, it is acquired as "commercial computer software" subject to the provisions of its applicable license agreement, as specified in (a) 48 CFR 12.212 of the FAR; or, if acquired for Department of Defense units, (b) 48 CFR 227-7202 of the DoD FAR Supplement; or sections succeeding thereto. Contractor/manufacturer is Silicon Graphics, Inc., 1600 Amphitheatre Pkwy 2E, Mountain View, CA 94043-1351. TRADEMARKS AND ATTRIBUTIONS Silicon Graphics, SGI, the SGI logo, IRIX, O2, Octane, and Origin are registered trademarks and OpenMP and ProDev are trademarks of Silicon Graphics, Inc. in the United States and/or other countries worldwide. MIPS, MIPS I, MIPS II, MIPS III, MIPS IV, R2000, R3000, R4000, R4400, R4600, R5000, and R8000 are registered or unregistered trademarks and MIPSpro, R10000, R12000, R1400 are trademarks of MIPS Technologies, Inc., used under license by Silicon Graphics, Inc. Portions of this publication may have been derived from the OpenMP Language Application Program Interface Specification.
    [Show full text]
  • Io — I/O Functions
    Title stata.com io — I/O functions Contents Description Remarks and examples Reference Also see Contents [M-5] Manual entry Function Purpose Console output printf( ) printf() display sprintf() display into string errprintf( ) errprintf() display error message display( ) display() display text interpreting SMCL displayas( ) displayas() set whether output is displayed displayflush( ) displayflush() flush terminal output buffer liststruct( ) liststruct() list structure’s contents more( ) more() create --more-- condition setmore() query or set more on or off setmoreonexit() set more on or off on exit File directories direxists( ) direxists() whether directory exists dir( ) dir() file list chdir( ) pwd() obtain current working directory chdir() change current working directory mkdir() make new directory rmdir() remove directory File management findfile( ) findfile() find file fileexists( ) fileexists() whether file exists cat( ) cat() read file into string matrix unlink( ) unlink() erase file adosubdir( ) adosubdir() obtain ado-subdirectory for file 1 2 io — I/O functions File I/O fopen( ) fopen() open file fclose() close file fget() read line of ASCII file fgetnl() same, but include newline character fread() read k bytes of binary file fput() write line into ASCII file fwrite() write k bytes into binary file fgetmatrix() read matrix fputmatrix() write matrix fstatus() status of last I/O command ftell() report location in file fseek() seek to location in file ftruncate() truncate file at current position ferrortext( ) ferrortext() error text of file error code freturncode()
    [Show full text]
  • JHDF5 (HDF5 for Java) 19.04
    JHDF5 (HDF5 for Java) 19.04 Introduction HDF5 is an efficient, well-documented, non-proprietary binary data format and library developed and maintained by the HDF Group. The library provided by the HDF Group is written in C and available under a liberal BSD-style Open Source software license. It has over 600 API calls and is very powerful and configurable, but it is not trivial to use. SIS (formerly CISD) has developed an easy-to-use high-level API for HDF5 written in Java and available under the Apache License 2.0 called JHDF5. The API works on top of the low-level API provided by the HDF Group and the files created with the SIS API are fully compatible with HDF5 1.6/1.8/1.10 (as you choose). Table of Content Introduction ................................................................................................................................ 1 Table of Content ...................................................................................................................... 1 Simple Use Case .......................................................................................................................... 2 Overview of the library ............................................................................................................... 2 Numeric Data Types .................................................................................................................... 3 Compound Data Types ................................................................................................................ 4 System
    [Show full text]
  • Software Process Validation: Quantitatively Measuring the Correspondence of a Process to a Model
    Software Process Validation: Quantitatively Measuring the Correspondence of a Process to a Model JONATHAN E. COOK New Mexico State University and ALEXANDER L. WOLF University of Colorado To a great extent, the usefulness of a formal model of a software process lies in its ability to accurately predict the behavior of the executing process. Similarly, the usefulness of an executing process lies largely in its ability to fulfill the requirements embodied in a formal model of the process. When process models and process executions diverge, something significant is happening. We have developed techniques for uncovering and measuring the discrepancies between models and executions, which we call process validation. Process validation takes a process execution and a process model, and measures the level of correspon- dence between the two. Our metrics are tailorable and give process engineers control over determining the severity of different types of discrepancies. The techniques provide detailed information once a high-level measurement indicates the presence of a problem. We have applied our process validation methods in an industrial case study, of which a portion is described in this article. Categories and Subject Descriptors: D.2.6 [Software Engineering]: Programming Environ- ments; K.6.3 [Management of Computing and Information Systems]: Software Manage- ment—software development; software maintenance General Terms: Management Additional Key Words and Phrases: Balboa, process validation, software process, tools This work was supported in part by the National Science Foundation under grants CCR-93- 02739 and CCR-9804067, and the Air Force Materiel Command, Rome Laboratory, and the Defense Advanced Research Projects Agency under Contract Number F30602-94-C-0253.
    [Show full text]
  • Oracle® Developer Studio 12.5
    ® Oracle Developer Studio 12.5: C User's Guide Part No: E60745 June 2017 Oracle Developer Studio 12.5: C User's Guide Part No: E60745 Copyright © 2016, 2017, Oracle and/or its affiliates. All rights reserved. This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited. The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing. If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, then the following notice is applicable: U.S. GOVERNMENT END USERS: Oracle programs, including any operating system, integrated software, any programs installed on the hardware, and/or documentation, delivered to U.S. Government end users are "commercial computer software" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, use, duplication, disclosure, modification, and adaptation of the programs, including any operating system, integrated software, any programs installed on the hardware, and/or documentation, shall be subject to license terms and license restrictions applicable to the programs.
    [Show full text]
  • Software Analysis Handbook: Software Complexity Analysis and Software Reliability Estimation and Prediction
    Technical Memorandum 104799 Software Analysis Handbook: Software Complexity Analysis and Software Reliability Estimation and Prediction Alice T. Lee Todd Gunn (NASA-TM-I04799) SOFTWARE ANALYSIS N95-I1914 Tuan Pham HANDBOOK: SOFTWARE COMPLEXITY Ron Ricaldi ANALYSIS AND SOFTWARE RELIABILITY ESTIMATION AND PREDICTION (NASA. Unclas Johnson Space Center) 96 p G3159 0023056 August 1994 ..0 National Aeronautics and Space Administration Technical Memorandum 104799 Software Analysis Handbook: Software Complexity Analysis and Software Reliability Estimation and Prediction Alice T. Lee Safety, Reliability, & Quaflty Assurance Office Lyndon B. Johnson Space Center Houston, Texas Todd Gunn, Tuan Pham, and Ron Ricaldi Loral Space Information Systems Houston, Texas National Aeronautics and Space Administration Thispublication is available from the NASA Center for AeroSpace Information, 800 Elkridge Landing Road, Linthicum Heights, MD 21090-2934, (301) 621-0390. Summary The purpose of this handbook is to document the software analysis process as it is performed by the Analysis and Risk Assessment Branch of the Safety, Reliability, and Quality Assurance Office at the Johnson Space Center. The handbook also provides a summary of the tools and methodologies used to perform software analysis. This handbook is comprised of two sepa- rate sections describing aspects of software complexity and software reliability estimation and prediction. The body of this document will delineate the background, theories, tools, and analysis procedures of these approaches. Software complexity analysis can provide quantitative information on code to the designing, testing, and maintenance organizations throughout the software life cycle. Diverse information on code structure, critical components, risk areas, testing deficiencies, and opportunities for improvement can be obtained using software complexity analysis.
    [Show full text]
  • CRTE V11.1A Common Runtime Environment
    English FUJITSU Software BS2000 CRTE V11.1A Common Runtime Environment User Guide * Edition December 2019 Comments… Suggestions… Corrections… The User Documentation Department would like to know your opinion on this manual. Your feedback helps us to optimize our documentation to suit your individual needs. Feel free to send us your comments by e-mail to: [email protected] senden. Certified documentation according to DIN EN ISO 9001:2015 To ensure a consistently high quality standard and user-friendliness, this documentation was created to meet the regulations of a quality management system which complies with the requirements of the standard DIN EN ISO 9001:2015 . Copyright and Trademarks Copyright © 2019 Fujitsu Technology Solutions GmbH. All rights reserved. Delivery subject to availability; right of technical modifications reserved. All hardware and software names used are trademarks of their respective manufacturers. Table of Contents CRTE V11.1 . 6 1 Preface . 7 1.1 Objectives and target groups of this manual . 8 1.2 Summary of contents . 9 1.3 Changes since the last edition of the manual . 10 1.4 Notational conventions . 11 2 Selectable unit, installation and shareability of CRTE . 12 2.1 CRTE V11.1A selectable unit . 13 2.2 Installing CRTE . 16 2.2.1 CRTE libraries for installation without version specification . 17 2.2.2 Standard installation under the user ID “$.” . 18 2.2.3 Installing with IMON under a non-standard user ID . 19 2.2.4 Installing header files and POSIX link switches in the default POSIX directory . 20 2.2.5 Installing header files and POSIX link switches in any POSIX directory .
    [Show full text]
  • Clostridium Difficile Infection: How to Deal with the Problem DH INFORMATION RE ADER B OX
    Clostridium difficile infection: How to deal with the problem DH INFORMATION RE ADER B OX Policy Estates HR / Workforce Commissioning Management IM & T Planning / Finance Clinical Social Care / Partnership Working Document Purpose Best Practice Guidance Gateway Reference 9833 Title Clostridium difficile infection: How to deal with the problem Author DH and HPA Publication Date December 2008 Target Audience PCT CEs, NHS Trust CEs, SHA CEs, Care Trust CEs, Medical Directors, Directors of PH, Directors of Nursing, PCT PEC Chairs, NHS Trust Board Chairs, Special HA CEs, Directors of Infection Prevention and Control, Infection Control Teams, Health Protection Units, Chief Pharmacists Circulation List Description This guidance outlines newer evidence and approaches to delivering good infection control and environmental hygiene. It updates the 1994 guidance and takes into account a national framework for clinical governance which did not exist in 1994. Cross Ref N/A Superseded Docs Clostridium difficile Infection Prevention and Management (1994) Action Required CEs to consider with DIPCs and other colleagues Timing N/A Contact Details Healthcare Associated Infection and Antimicrobial Resistance Department of Health Room 528, Wellington House 133-155 Waterloo Road London SE1 8UG For Recipient's Use Front cover image: Clostridium difficile attached to intestinal cells. Reproduced courtesy of Dr Jan Hobot, Cardiff University School of Medicine. Clostridium difficile infection: How to deal with the problem Contents Foreword 1 Scope and purpose 2 Introduction 3 Why did CDI increase? 4 Approach to compiling the guidance 6 What is new in this guidance? 7 Core Guidance Key recommendations 9 Grading of recommendations 11 Summary of healthcare recommendations 12 1.
    [Show full text]
  • 15-122: Principles of Imperative Computation, Fall 2014 Lab 11: Strings in C
    15-122: Principles of Imperative Computation, Fall 2014 Lab 11: Strings in C Tom Cortina(tcortina@cs) and Rob Simmons(rjsimmon@cs) Monday, November 10, 2014 For this lab, you will show your TA your answers once you complete your activities. Autolab is not used for this lab. SETUP: Make a directory lab11 in your private 15122 directory and copy the required lab files to your lab11 directory: cd private/15122 mkdir lab11 cp /afs/andrew.cmu.edu/usr9/tcortina/public/15122-f14/*.c lab11 1 Storing and using strings using C Load the file lab11ex1.c into a text editor. Read through the file and write down what you think the output will be before you run the program. (The ASCII value of 'a' is 97.) Then compile and run the program. Be sure to use all of the required flags for the C compiler. Answer the following questions on paper: Exercise 1. When word is initially printed out character by character, why does only one character get printed? Exercise 2. Change the program so word[3] = 'd'. Recompile and rerun. Explain the change in the output. Run valgrind on your program. How do the messages from valgrind correspond to the change we made? Exercise 3. Change word[3] back. Uncomment the code that treats the four character array word as a 32-bit integer. Compile and run again. Based on the answer, how are bytes of an integer stored on the computer where you are running your code? 2 Arrays of strings Load the file lab11ex2.c into a text editor.
    [Show full text]
  • Unix (And Linux)
    AWK....................................................................................................................................4 BC .....................................................................................................................................11 CHGRP .............................................................................................................................16 CHMOD.............................................................................................................................19 CHOWN ............................................................................................................................26 CP .....................................................................................................................................29 CRON................................................................................................................................34 CSH...................................................................................................................................36 CUT...................................................................................................................................71 DATE ................................................................................................................................75 DF .....................................................................................................................................79 DIFF ..................................................................................................................................84
    [Show full text]