Unix and C Program Development SEEM

Similar documents
C Program Development and Debugging under Unix SEEM 3460

The make Utility in Unix SEEM

The make Utility in Unix SEEM

Laboratory 1 Semester 1 11/12

Operating Systems, Unix Files and Commands SEEM

Problem Set 1: Unix Commands 1

Intermediate Programming, Spring Misha Kazhdan

Practical Session 0 Introduction to Linux

We first learn one useful option of gcc. Copy the following C source file to your

CSE 351. GDB Introduction

Chapter-3. Introduction to Unix: Fundamental Commands

CS Fundamentals of Programming II Fall Very Basic UNIX

Introduction to Linux (Part II) BUPT/QMUL 2018/03/21

Unix Internal Assessment-2 solution. Ans:There are two ways of starting a job in the background with the shell s & operator and the nohup command.

Using the Unix system. UNIX Introduction

Getting started with UNIX/Linux for G51PRG and G51CSA

CSC111 Computer Science II

TNM093 Practical Data Visualization and Virtual Reality Laboratory Platform

CMPUT 201: Practical Programming Methodology. Guohui Lin Department of Computing Science University of Alberta September 2018

What are some common categories of system calls? What are common ways of structuring an OS? What are the principles behind OS design and

Linux Command Line Primer. By: Scott Marshall

The Unix Shell & Shell Scripts

Linux/Cygwin Practice Computer Architecture

Lecture 1. A. Sahu and S. V. Rao. Indian Institute of Technology Guwahati

Operating Systems. Copyleft 2005, Binnur Kurt

Introduction to Linux. Fundamentals of Computer Science

Operating Systems 3. Operating Systems. Content. What is an Operating System? What is an Operating System? Resource Abstraction and Sharing

Using the Zoo Workstations

Jackson State University Department of Computer Science CSC / Advanced Information Security Spring 2013 Lab Project # 5

15-122: Principles of Imperative Computation

commandname flags arguments

EKT332 COMPUTER NETWORK

Introduction to Linux

Getting Started. Running Utilities. Shells. Special Characters. Special Characters. Chapter 2 Unix Utilities for non-programmers

CSE 303 Lecture 2. Introduction to bash shell. read Linux Pocket Guide pp , 58-59, 60, 65-70, 71-72, 77-80

Oxford University Computing Services. Getting Started with Unix

Exploring UNIX: Session 3

Overview LEARN. History of Linux Linux Architecture Linux File System Linux Access Linux Commands File Permission Editors Conclusion and Questions

Introduction to Linux Workshop 1

Computers and Computation. The Modern Computer. The Operating System. The Operating System

Crash Course in Unix. For more info check out the Unix man pages -orhttp:// -or- Unix in a Nutshell (an O Reilly book).

Introduction to UNIX. Logging in. Basic System Architecture 10/7/10. most systems have graphical login on Linux machines

Introduction p. 1 Who Should Read This Book? p. 1 What You Need to Know Before Reading This Book p. 2 How This Book Is Organized p.

CSC209. Software Tools and Systems Programming.

Beyond this course. Machine code. Readings: CP:AMA 2.1, 15.4

Mills HPC Tutorial Series. Linux Basics I

Lab 1 Introduction to UNIX and C

Introduction to Linux. Woo-Yeong Jeong Computer Systems Laboratory Sungkyunkwan University

Princeton University COS 217: Introduction to Programming Systems GDB Tutorial and Reference

Introduction to Unix: Fundamental Commands

Contents. Note: pay attention to where you are. Note: Plaintext version. Note: pay attention to where you are... 1 Note: Plaintext version...

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

Saint Louis University. Intro to Linux and C. CSCI 2400/ ECE 3217: Computer Architecture. Instructors: David Ferry

CS 215 Fundamentals of Programming II Spring 2019 Very Basic UNIX

Exercise 1: Basic Tools

Basic File Attributes

The kernel is the low-level software that manages hardware, multitasks programs, etc.

Program Design: Using the Debugger

CSCI0330 Intro Computer Systems Doeppner. Lab 02 - Tools Lab. Due: Sunday, September 23, 2018 at 6:00 PM. 1 Introduction 0.

Introduction to the Command line. Introduction to the command line. Introduction to the Command line. GNU/Linux at South Wales

Unix Workshop Aug 2014

CS370 Operating Systems

EL2310 Scientific Programming

CSE 374 Programming Concepts & Tools. Brandon Myers Winter 2015 Lecture 11 gdb and Debugging (Thanks to Hal Perkins)

System Programming. Introduction to Unix

CHAPTER 1 UNIX FOR NONPROGRAMMERS

Unix Filesystem. January 26 th, 2004 Class Meeting 2

Linux Training. for New Users of Cluster. Georgia Advanced Computing Resource Center University of Georgia Suchitra Pakala

1. The Mac Environment in Sierra Hall 1242

Using LINUX a BCMB/CHEM 8190 Tutorial Updated (1/17/12)

CMPT 300. Operating Systems. Brief Intro to UNIX and C

Lab 1 Introduction to UNIX and C

INTRODUCTION TO BIOINFORMATICS

Lecture 03 Bits, Bytes and Data Types

EL2310 Scientific Programming

Introduction to Linux

Using UNIX. -rwxr--r-- 1 root sys Sep 5 14:15 good_program

UNIX Quick Reference

Unix Tutorial Haverford Astronomy 2014/2015

CSCE 212H, Spring 2008, Matthews Lab Assignment 1: Representation of Integers Assigned: January 17 Due: January 22

Introduction to the Linux Command Line

Perl and R Scripting for Biologists

Princeton University COS 217: Introduction to Programming Systems GDB Tutorial and Reference for x86-64 Assembly Language

Introduction. SSH Secure Shell Client 1

Introduction to Supercomputing

Introduction to Linux

EECS2301. Lab 1 Winter 2016

Linux File System and Basic Commands

Introduction to Linux Environment. Yun-Wen Chen

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview

CS354 gdb Tutorial Written by Chris Feilbach

CS Unix Tools. Fall 2010 Lecture 10. Hussam Abu-Libdeh based on slides by David Slater. September 29th, 2010

CSCI 2132 Software Development. Lecture 3: Unix Shells and Other Basic Concepts

Unix File System. Class Meeting 2. * Notes adapted by Joy Mukherjee from previous work by other members of the CS faculty at Virginia Tech

CS140 Operating Systems Final December 12, 2007 OPEN BOOK, OPEN NOTES

Operating System Interaction via bash

1. The Mac Environment in SIE 1222

Temple University Computer Science Programming Under the Linux Operating System January 2017

CSCI 2132 Software Development. Lecture 4: Files and Directories

CMSC 104 Lecture 2 by S Lupoli adapted by C Grasso

Transcription:

Unix and C Program Development SEEM 3460 1

Operating Systems A computer system cannot function without an operating system (OS). There are many different operating systems available for PCs, minicomputers, and mainframes. The most common ones being Windows and variations of UNIX (e.g. Linux) UNIX is available for many different hardware platforms Most other operating systems are tied to a specific hardware family. This is one of the first good things about UNIX. SEEM 3460 2

Unix Overview UNIX allows more than one user to use the computer system at a time a desirable feature for business systems. Power and Flexibility Small number of basic elements that can be combined in an infinite variety of ways to suit the application Consistency in commands: ls A* means list files beginning with A rm A* means remove files beginning with A Majority of users are engaged in software development SEEM 3460 3

Unix and Linux Late 1980s two version of UNIX 4.3BSD System V Release 3 Standardizing effort POSIX (Portable Operating System) POSIX committee produced standard 1003.1 by taking the intersection of System V and BSD Set of library procedures open, read, fork, Linux Unix clone originally running on PC Recent Version of Linux has features of a modern UNIX OS Unix and Linux have been adopted in industrialstrength business applications SEEM 3460 4

Unix and Shell MAC and Windows - Graphical User Interface UNIX command line interface, called shell UNIX Graphical environment X Windows SEEM 3460 5

Logging In To use a UNIX system, you first log in with a username a unique name that distinguishes you from the other users of the system. UNIX first asks you for your username by prompting you with the line login: and then asks for your password. Depending on how your system is set up, you should then see either a $ or a > prompt. UNIX is case sensitive, so make sure that the case of the letters is matched exactly. UNIX(r) System V Release 4.0 login: glass Password: what I typed here is secret and doesn t show Last login: Sun Feb 15 18:33:26 from dialin cuse93:> SEEM 3460 6

Shells The > prompt that you see when you first log into UNIX is displayed by the shell Shell is a program that acts as a middleman between you and the raw UNIX operating system. A shell lets you run programs, builds pipelines of processes, saves output to files, and runs more than one program at the same time. SEEM 3460 7

Running A Utility To run a utility, simply enter its name and press the Enter key One sample utility is date which displays the current date and time cuse93:> date... run the date utility Thu Mar 12 10:41:50 MST 1998 cuse93:> SEEM 3460 8

Unix Utility Programs Large number of utility programs Divided into six categories File and directory manipulation commands Example: cp a b ls *.* Filters Example: grep (extracts lines containing patterns), cut, paste, Program development tools such as editors/compilers Example: cc (C compiler), make (maintain large programs whose source code consists of multiple files) Text editing and processing Example: pico, emacs, vim, vi System administration Example: mount (mount file system) Miscellaneous Example: kill 1325 (kill a process), chmod (change privileges of a file) SEEM 3460 9

Unix Utility Programs SEEM 3460 10

Logging Out To leave the UNIX system, type the keyboard sequence Control-D at your shell prompt. This tells your login shell that there is no more input for it to process, causing it to disconnect you from the UNIX system. Most systems then display a prompt and wait for another user to log in. Here s an example: cuse93:> ^D... I m done! UNIX(r) System V Release 4.0 login: wait for another user to log in. Note: The shell can be set to ignore ^D for logout, since you might type it by accident. In this case, you in, type the logout command instead. SEEM 3460 11

Directory and File A hard disk in Unix is typically shared by different users Directory similar to folder in Windows The root directory is specified by a symbol / Under a directory Store files Contains sub-directories SEEM 3460 12

Directories The directories are organized in a hierarchical structure (similar to Windows) / usr sac lec file1 glass file2 wlam SEEM 3460 13

Pathname Pathname - A sequence of directory names that leads you through the hierarchy from a starting directory (e.g. root / ) to a target (directory or file) Some sample pathnames /sac/file1 a file /sac/lec a directory /sac/lec/file2 a file SEEM 3460 14

Home Directory When you first login, you are automatically located at a certain location of a hard disk called home directory Every user has a different home directory The home directory is set by the system administrator For example, after login, the user is located at /sac/lec/glass UNIX(r) System V Release 4.0 login: glass Password: what I typed here is secret and doesn t show Last login: Sun Feb 15 18:33:26 from dialin cuse93:/sac/lec/glass> SEEM 3460 15

Unix - Making A Directory : mkdir We can use the mkdir utility to create a new directory. An example of the mkdir utility: Utility: mkdir newdirectoryname cuse93:> mkdir reverse... create a directory called reverse cuse93:> SEEM 3460 16

Unix - Moving To A Directory : cd In general, it s a good idea to move your shell into a directory if you intend to do a lot of work there. To do this, use the cd command. cuse93:> cd reverse go to the reverse directory cd isn t actually a UNIX utility, but instead is an example of a shell built-in command. Your shell recognizes cd as a special keyword and executes it directly. Shell Command: cd [directoryname] The cd (change directory) shell command changes a shell s current working directory to directoryname. If the directoryname argument is omitted, the shell is moved to its owner s home directory. SEEM 3460 17

Editing Programs: Using an Editor pico Editor General Command Write editor contents to a file [Ctrl] o Save the file and exit pico [Ctrl] x Spell Check [Ctrl] t Justify the text [Ctrl] j Moving around in your file Move one character to the right [Ctrl] f or right arrow key Move one character to the left [Ctrl] b or left arrow key Move up one line [Ctrl] p or up arrow key Move down one line [Ctrl] n or down arrow key Other editors such as emacs and vim can be used SEEM 3460 18

Unix - Listing The Contents Of A Directory: ls We can use the ls utility to list the name and other information about a file or a directory. Suppose that we have used an editor to edit the program reverse.c cuse93:> ls list all files in current directory reverse.c cuse93:> ls -l reverse.c long listing of reverse.c -rw-r--r-- 1 glass 106 Jan 30 19:46 reverse.c The -l is an option for the ls utility SEEM 3460 19

Unix - Listing A File: cat We can use the cat utility to display the content of a text file. cuse93:> cat reverse.c display the contents of the reverse.c /* reverse.c */ #include <stdio.h> /* Function prototype */ void reverse (char* before, char* after); /*******************************************/ int main() { char str[100]; /* buffer to hold reversed string */ reverse("cat",str); /* reverse the string "cat" */ printf ("reverse("cat") = %s\n", str); : : SEEM 3460 20

Unix - Listing A File: more cat is good for listing small files, but doesn t pause between full screens of output. The more utility is better suited for larger files and contains advanced facilities such as the ability to scroll backward through a file. cuse93:> more reverse.c display the contents of the reverse.c /* reverse.c */ #include <stdio.h> /* Function prototype */ void reverse (char* before, char* after); /*******************************************/ int main() : : SEEM 3460 21

Computer System C Compiler Assembler seg3460 Introduction 22

Computer System Each type of CPU executes only a particular machine language A program must be translated into machine language before it can be executed A compiler is a software tool which translates source code into a specific target language Often, that target language is the machine language for a particular CPU type SEEM 3460 23

Program Development The mechanics of developing a program include several activities writing the program in a specific programming language (such as C and Java) translating the program into a form that the computer can execute investigating and fixing various types of errors that can occur Software tools can be used to help with all parts of this process SEEM 3460 24

Basic Program Development Edit and save program errors errors Compile program Execute program and evaluate results SEEM 3460 25

Single-module Programs Let s examine a C program that performs a simple task: reversing a string. We will learn how to write, compile, link, and execute a program that solves the problem using a single source file. It s better to split the program up into several independent modules. (will be explained later) A source code listing of the first version of the reverse program is next presented. SEEM 3460 26

1 /* reverse.c */ 2 #include <stdio.h> 3 4 /* Function prototype */ 5 void reverse (char* before, char* after); 6 7 /*******************************************/ 8 int main() 9 { 10 char str[100]; /* buffer to hold reversed string */ 11 reverse("cat",str); /* reverse the string "cat" */ 12 printf ("reverse("cat") = %s\n", str); 13 reverse("noon",str); 14 printf ("reverse("noon") = %s\n", str); 15 } 16 17 /*******************************************/ 18 void reverse (char* before, char* after) 19 { 20 int i,j,len; 21 22 len = strlen(before); 23 i=0; 24 for (j=len-1; j>=0; j--) 25 { 26 after[i] = before[j]; 27 i++; 28 } 29 after[len] = NULL; 30 } SEEM 3460 27

C String - Revision In C, a string is represented as an array of characters For example: noon is represented as: 0 1 2 3 4 5 n o o n NULL (special char) X (garbage) SEEM 3460 28

C Program Development First we need to type the program source code into a file called source file (or source program file). Suppose that we call this file reverse.c The format of the source file should be a text file since it contains text characters A text file in Unix can be created using an Unix editor such as emacs, pico, vim. Suppose that we first create a directory (folder) called reverse under my home directory to prepare the development of the program. SEEM 3460 29

C Compilers Until recently, a C compiler was a standard component in UNIX, especially UNIX versions that came with source code. Depending on your needs, you should check on this in any version of UNIX you are considering using. Even if your version of UNIX no longer ships a C compiler, you have an alternative, thanks to the GNU Project: GNU C (gcc) and GNU C++ (g++) are freely available C and C++ compilers, respectively GNU Compiler Collection web site, http://www.gnu.org/software/gcc/gcc.html SEEM 3460 30

Compiling a C program Compile the C program with the gcc utility. By default, gcc creates an executable file called a.out in the current directory. The format of executable file is called binary file which contains binary bits. Therefore, we cannot use the Unix utilities cat or more to display the content on the screen. To run the program, type./a.out. Any errors that are encountered are sent to the standard error channel, which is connected by default to your terminal s screen. SEEM 3460 31

Compiling a C program (con t) Here s what happened when I compiled my program: cuse93:> mkdir reverse create subdirectory for source code cuse93:> cd reverse cuse93:> pico reverse.c... create the file reverse.c using pico cuse93:> gcc reverse.c... compile source. reverse.c: In function main : reverse.c:12: parse error before cat reverse.c:14: parse error before noon cuse93:> As you can see, gcc found a number of compile-time errors, listed together with their causes as follows: The errors on lines 12 and 14 were due to an inappropriate use of double quotes within double quotes. SEEM 3460 32

Compiling a C program (con t) If there are so many compilation errors that it cannot fit into one screen. One way is to compile by the following command: gcc reverse.c & more which means that the compilation errors will be displayed screen by screen. It will display the first screen of errors and wait. After the user examines the errors, he/she can choose to display the next screen of errors by hitting RETURN or quit by hitting Control-C. The corrected version of the reverse program is given in the next page. SEEM 3460 33

1 /* reverse.c */ 2 #include <stdio.h> 3 4 /* Function prototype */ 5 void reverse (char* before, char* after); 6 7 /*******************************************/ 8 int main() 9 { 10 char str[100]; /* buffer to hold reversed string */ 11 reverse("cat",str); /* reverse the string "cat" */ 12 printf ("reverse(\"cat\") = %s\n", str); 13 reverse("noon",str); 14 printf ("reverse(\"noon\") = %s\n", str); 15 } 16 17 /*******************************************/ 18 void reverse (char* before, char* after) 19 { 20 int i,j,len; 21 22 len = strlen(before); 23 i=0; 24 for (j=len-1; j>=0; j--) 25 { 26 after[i] = before[j]; 27 i++; 28 } 29 after[len] = NULL; 30 } SEEM 3460 34

Compiling a C program (con t) If there are many compilation errors, it is a good strategy to debug the first few errors since some remaining compilation errors may not be actual errors. They exist due to the limitations of the compiler. Hence, fixing earlier errors will usually result in fewer errors encountered in the debugging process. e.g. a semicolon is mistakenly added after the function heading line of reverse would produce a lot of compilation errors. SEEM 3460 35

Compiling a C program (con t) Running a C Program After compiling the second version of reverse.c, I ran it by typing the name of the executable file, a.out. As you can see, the answers were correct: cuse93:> gcc reverse.c compile source. cuse93:> ls l reverse.c a.out list file information. -rwxr-xr-x 1 glass 24576 Jan5 16:16 a.out* -rw----r-- 1 glass 439 Jan 5 16:15 reverse.c cuse93:>./a.out run program reverse ( cat ) = tac reverse ( noon ) = noon cuse93:> SEEM 3460 36

Compiling a C program (con t) Overriding the Default Executable Name The name of the default executable file, a.out, is rather cryptic, and an a.out file produced by a subsequent compilation would overwrite the one that I just produced. To avoid both problems, it s best to use the -o option with gcc, which allows you to specify the name of the executable file that you wish to create: cuse93:> gcc -o reverse reverse.c name the executable reverse cuse93:> ls -l reverse -rwxr-xr-x 1 glass 24576 Jan 5 16:19 reverse* cuse93:>./reverse run the executable reverse reverse ( cat ) = tac reverse ( noon ) = noon cuse93:> SEEM 3460 37

Summary of gcc utility gcc reverse.c source file: reverse.c compilation via gcc executable file: a.out gcc o reverse reverse.c source file: reverse.c compilation via gcc executable file: reverse 38

Syntax and Semantics The syntax rules of a language define how we can put together symbols, reserved words, and identifiers to make a valid program The semantics of a program statement define what that statement means (its purpose or role in a program) A program that is syntactically correct is not necessarily logically (semantically) correct A program will always do what we tell it to do, not only what we intend to tell it to do 39

Program Errors A program can have three types of errors The compiler will find syntax errors and other basic problems (compile-time errors) If compile-time errors exist, an executable version of the program is not created A problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally (run-time errors) A program may run, but produce incorrect results, perhaps using an incorrect formula (logical errors) 40

Program Errors In Unix, many runtime errors and logical errors only provide the following error messages: Segmentation fault Bus error The above messages do not provide good hints for the causes of the error In other words, it is almost not useful to rely on this message for debugging Therefore, debugging techniques or tools are needed Inserting printing statements to display the content of variables Use a debugger utility SEEM 3460 41

Debugging by Inserting printing Statements A good way for debugging is to insert printing statements in the program. The purpose is to print the content of some important variables to see if the execution follows our design. Suppose we inserted the following line after the statement i++ in the reverse function: printf( i=%d j=%d\n,i,j) The execution would look like: cuse93:>./reverse run the executable reverse i = 1 j = 2 i = 2 j = 1 i = 3 j = 0 reverse ( cat ) = tac i = 1 j = 3 : SEEM 3460 42

Debugging by Inserting printing Statements (cont) When the output text to the screen is very long, we can re-direct the output text to a file instead of the screen so that we can examine the content in a more convenient way. To re-direct in Unix the output from the screen to a text file, we can use the character > meaning that the text output is re-directed from the system output (screen) to a specified text file. In the following example, it is re-directed to a text file called debug.txt cuse93:>./reverse > debug.txt run the executable reverse cuse93:> more debug.txt i = 1 j = 2 i = 2 j = 1 i = 3 j = 0 reverse ( cat ) = tac i = 1 j = 3 : SEEM 3460 43

The Unix Debugger : gdb Preparing a Program for Debugging To debug a program, it must have been compiled using the -g option to gcc, which places debugging information into the object module. cuse93:> gcc g o reverse reverse.c The UNIX debugger, gdb, allows you to debug a program symbolically. It includes the following facilities: single stepping breakpoints editing from within the debugger accessing and modifying variables searching for functions tracing SEEM 3460 44

The Unix Debugger : gdb (con t) Utility: gdb executablefilename gdb is a UNIX debugger. The named executable file is loaded into the debugger and a user prompt is displayed. To obtain information on the various gdb commands, enter help at the prompt. Entering the Debugger Once a program has been compiled correctly, you may invoke gdb, with the name of the executable file as the first argument. gdb presents you with a prompt. You enter help at the prompt to see a list of all the gdb commands: cuse93:> gdb reverse (gdb) help SEEM 3460 45

The Unix Debugger : gdb (con t) (gdb) break reverse Breakpoint 1 at 0x1077c: file reverse.c, line 22 (gdb) run Starting program: reverse Breakpoint 1, reverse(before=0x11360 ) at reverse.c:22 22 len = strlen(before) (gdb) display i 1: i=0 (gdb) display j 2: j = -4197908 (gdb) step 23 i = 0; 2: j = -4197908 1: i = 0 (gdb) step 24 for (j=len-1; j>=0; j--) 2: j = -4197908 1: i = 0 (gdb) step 26 after [i] = before [j] 2: j = 2 1: i = 0 SEEM 3460 46

The Unix Debugger : gdb (con t) (gdb) continue Continuing. reverse( cat ) = tac Breakpoint 1, reverse (before = 0x11380.) at reverse.c:22 22 len = strlen(before); 2: j = -1 1: i = 3 (gdb) step 23 i = 0; 2: j = -1 1: i = 3 (gdb) step 24 for (j=len-1; j>=0; j--) 2: j = -1 1: i = 0 (gdb) continue Continuing. Reverse( noon ) = noon Program exited with code 01 SEEM 3460 47