CSC 2405: Computer Systems II

Similar documents
CSC Execution Environment. Program Execution Environment

Standard File Pointers

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

File IO and command line input CSE 2451

C programming basics T3-1 -

2009 S2 COMP File Operations

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

8. Characters, Strings and Files

Lecture 7: Files. opening/closing files reading/writing strings reading/writing numbers (conversion to ASCII) command line arguments

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

Week 2 Intro to the Shell with Fork, Exec, Wait. Sarah Diesburg Operating Systems CS 3430

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Recitation 2/18/2012

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

Understanding Pointers

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

File Access. FILE * fopen(const char *name, const char * mode);

Memory Layout, File I/O. Bryce Boe 2013/06/27 CS24, Summer 2013 C

File I/O, Project 1: List ADT. Bryce Boe 2013/07/02 CS24, Summer 2013 C

Review Topics. Final Exam Review Slides

Programming & Data Structure

Contents. A Review of C language. Visual C Visual C++ 6.0

CSE 303 Midterm Exam

File I/O. Arash Rafiey. November 7, 2017

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

File Handling. 21 July 2009 Programming and Data Structure 1

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Standard C Library Functions

C mini reference. 5 Binary numbers 12

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

Lecture 03 Bits, Bytes and Data Types

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Information Sciences and Engineering

mith College Computer Science CSC231 Bash Labs Week #10, 11, 12 Spring 2017 Introduction to C Dominique Thiébaut

211: Computer Architecture Summer 2016

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

PROGRAMMAZIONE I A.A. 2017/2018

CSC 2400: Computer Systems. Arrays and Strings in C

CSE 303 Lecture 15. C File Input/Output (I/O) reading: Programming in C Ch. 16; Appendix B pp

CSCI 171 Chapter Outlines

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CS1003: Intro to CS, Summer 2008

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

CSC 2400: Computer Systems. Arrays and Strings in C

Chapter 14 - Advanced C Topics

CS 261 Fall Mike Lam, Professor. Structs and I/O

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

THE C STANDARD LIBRARY & MAKING YOUR OWN LIBRARY. ISA 563: Fundamentals of Systems Programming

Systems Programming. 08. Standard I/O Library. Alexander Holupirek

Today s Learning Objectives

Topic 8: I/O. Reading: Chapter 7 in Kernighan & Ritchie more details in Appendix B (optional) even more details in GNU C Library manual (optional)

Characters and Strings

M.CS201 Programming language

CSCI-243 Exam 2 Review February 22, 2015 Presented by the RIT Computer Science Community

SU2017. LAB 1 (May 4/9) Introduction to C, Function Declaration vs. Definition, Basic I/O (scanf/printf, getchar/putchar)

Fall 2015 COMP Operating Systems. Lab #3

PRINCIPLES OF OPERATING SYSTEMS

Pointers and File Handling

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Administrative Stuff. More on Strings, File I/O. Last Time. Java API

More on Strings, File I/O. September 8, 2016

CSE 374 Programming Concepts & Tools

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

High Performance Programming Programming in C part 1

Goals of this Lecture

Chapter 8 C Characters and Strings

25.2 Opening and Closing a File

I/O Management! Goals of this Lecture!

UNIT IV-2. The I/O library functions can be classified into two broad categories:

I/O Management! Goals of this Lecture!

Intermediate Programming, Spring 2017*

Model Viva Questions for Programming in C lab

File I/O. Preprocessor Macros

CS 5513 Entry Quiz. Systems Programming (CS2213/CS3423))

CP2 Revision. theme: file access and unix programs

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

Pointer Arithmetic and Lexical Scoping. CS449 Spring 2016

CE Lecture 11

Array Initialization

In the case of the dynamic array, the space must be deallocated when the program is finished with it. free(x);

CS240: Programming in C

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

Lecture 05 Pointers ctd..

COP Programming Concepts Spring 1999 CLOSED BOOK Exam #1 100 Points NAME

Computational Methods of Scientific Programming Fall 2007

Introduction. Files. 3. UNIX provides a simple and consistent interface to operating system services and to devices. Directories

Input/Output and the Operating Systems

Chapter 9 Strings. With this array declaration: char s[10];

Basic and Practice in Programming Lab 10

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Transcription:

CSC 2405: Computer Systems II Program Execution Environment Execution Environment The main func*on is the entry point for C program execu*on int main( int argc, char * argv[]); The linker (called by the C compiler) specifies, in the executable program file, a special start- up rou*ne to be called before main The start- up rou*ne takes command line arguments and environment values from the kernel sets things up so that main is then called 1

Environment When a UNIX program is executed, it receives two pieces of data: the arguments the environment To C programs, both are arrays of character pointers all but the last of the character pointers point to a NULL- terminated string the last pointer is a NULL pointer A count of the number of arguments (not including the NULL pointer) is also passed Memory Layout of a C Program Low Address Text Data BSS Heap Stack High Address Command-Line Arguments and Environment Variables 2

Environment The global variable environ points to the array of environment strings (whose last entry is NULL) extern char **environ; /* environment array (not in any header) */ Environment One way to access the environment strings is to use the environ variable directly. Each environment string is of the form name=value extern char **environ; int main(int argc, char *argv[]) { } int i; for (i=0; environ[i]!= 0; i++) printf("%s\n",environ[i]); return 0; 3

Environment Example PWD=/mnt/a/mdamian/Systems/Shell TZ=US/Eastern HOSTNAME=tanner USER=mdamian MACHTYPE=sparc-sun-solaris2.9 OLDPWD=/mnt/a/mdamian/Systems LOGNAME=mdamian SHLVL=1 SHELL=/bin/bash HOSTTYPE=sparc OSTYPE=solaris2.9 HOME=/mnt/a/mdamian TERM=vt100 PATH=/usr/ccs/bin:/home2/jdk1.5.0/bin:/usr/sbin:/ opt/gnu/bin:/usr/bin:/opt/local/bin:/usr/local/ bin:.:/usr/ccs/bin:/usr/bin:/bin:/usr/sbin:/sbin:/ usr/gnu/bin:/usr2/local/bin:/mnt/local/bin:/usr/ucb SSH_TTY=/dev/pts/6 getenv Call Lis*ng an en*re environment is an unusual requirement Typically, the value for one environment variable is needed #include <stdlib.h> char *getenv(const char * var); var is the variable to find returns value or NULL if not found 4

getenv Example #include <stdio.h> #include <stdlib.h> int main(void) { char *s; s = getenv("logname"); if (s == NULL) printf("variable not found\n"); else printf("value is \"%s\"\n",s); } exit(exit_success); Some Environment variables Name HOME USER HOSTNAME PWD PATH Description your home directory your login ID the name of the host computer the current working directory a list of directories in which to look for executable commands 5

man Command: Your Best Friend Syntax is man command Shows information about the command Usually it takes multiple screens, so hit Space or Enter for more information When done, hit q to quit Hands On Part One In your systems directory, create another directory called environ In your directory systems/environ, write a program called env.c that retrieves the value of your HOME directory and prints it out. Sample execution: My home directory is /mnt/a/mdamian Extend your code to also print out the value of your current working directory (environ variable PWD). Sample execution: My current directory is /mnt/a/mdamian/systems/environ 6

C Standard Library Function: strtok The strtok Function char * strtok(char *s, char * delim); delim contains all characters separating the tokens if s is non-null: return pointer to beginning of first token in s, and terminate token with NULL. If s is NULL: use remainder of untokenized string from the last call to strtok 7

strtok in Action char * token; token = strtok(line,,; ); while(token!= NULL) { printf( Token is [%s]\n, token); token = strtok(null,,; ); } d o g, c a t ; NULL line token strtok in Action After first call token = strtok(line,,; ); d o g NULL c a t ; NULL line token Output is Token is [dog] 8

strtok in Action After second call token = strtok(null,,; ); d o g NULL c a t NULL NULL line token Output is Token is [cat] strtok in Action After third call token = strtok(null,,; ); the loop breaks. d o g NULL c a t NULL NULL line NULL token 9

What is the Output? #define MAX 80 char buf[max]; char * token; sprintf(buf, "%s", "This.is.my.strtok.test\n"); token = strtok(buf, ".\n"); printf("[%s], [%s] ", buf, token); token = strtok(null, ".\n"); printf("[%s], [%s] ", buf, token); token = strtok(null, ".\n"); printf("[%s], [%s] ", buf, token); token = strtok(buf, ".\n"); printf("[%s], [%s] ", buf, token); Hands On Part Two In your directory systems/environ, write a program called pathenv.c that retrieves the value of the PATH variable from the program environment, then prints out all search paths, one per line (use strtok). Sample execution: The shell search paths are: /usr/ccs/bin /home2/jdk1.5.0/bin /opt/gnu/bin /usr/sbin /usr/bin /opt/local/bin /usr/local/bin 10

Hands On Part Three Make a copy of your pathenv program (call it pathenvcopy). Then edit your original pathenv program to save the search paths in an array of strings before printing them out. More precisely, your program should do the following: 1. Retrieve the value of the PATH variable 2. Copy this string into a local buffer (use strcpy) 3. Extract the tokens and save them in an array of pointers:... NULL "/opt/gnu/bin" "/home2/jdk1.5.0/bin" "/usr/ccs/bin" 4. Print out each string in the array Hands On Part Four Reorganize your code from part three to include threefunctions void tokenize_path(); /* build the array of paths*/ void print_path(); /* print the paths */ void free_path(); /* deallocate the array */ The first function builds the array of search paths. The second function prints the paths, one per line. The main function should simply call these functions: int main(int argc, char * argv[]) { tokenize_path(); print_path(); free_path(); return 0; } Make sure the array of search paths is a GLOBAL variable, so that other functions (to be added later) can access it. 11

C Standard Library Function: fopen fclose File Input and Output So far, all input and output has been to standard input and from standard output: scanf() or getchar() or fgets(..., stdin) printf() or putchar() In most application and professional situations, you will need to read from/write to files 12

File I/O in C Before you can access a file you must open it! After you are done, you must close it! Synopsis #include <stdio.h> FILE *fp; FILE *fopen(char *name, char *mode); int fclose(file *fp); A data type defined in <stdio.h> The mode of access. The path name of the file FILE *fopen(char *name, char *mode) name may be Fully qualified: /tmp/code.c Relative to working directory:./fopen.pdf mode may be "r" read only "w" write only (create or discard previous contents) "a" append only (write at end; create if necessary) "r+" read and update (i.e., read-write) "w+" read-write (create or discard previous contents) "a+" read-append (write at end; create if necessary) Add "b" to mode string for binary files, e.g. rb, wb Returns NULL if the file does not exist 13

Hands On Part Five Extend your pathenv.c program with a function int file_exists(char * filepath); that returns 1 if the file with the given path exists and 0 otherwise. Hint: check out the value returned by fopen Add code to the main function to test out the file_exists function. Keep it simple. Hands On Part Six Extend your pathenv.c program with a function void find_path(char * filename); that prints out the directory containing the file given as argument. To do so: 1. Allocate a static buffer (e.g., char buf[100];) 2. In a loop over the search paths: a) Copy the next search path in the local buffer (use strcpy) b) Append the filename to the search path (use strcat) c) Check if the resulted file path exists (use file_exists) d) If the answer is yes, print the search path and return e) If the answer is no, continue the loop 14

Example: find_path( gcc )... NULL "/opt/gnu/bin" "/home2/jdk1.5.0/bin" "/usr/ccs/bin" searchpaths buf /usr/ccs/bin/gcc strcpy strcat file_exists(buf) returns 0 Example: find_path( gcc )... NULL searchpaths "/opt/gnu/bin" "/home2/jdk1.5.0/bin" "/usr/ccs/bin" buf /home2/jdk1.5.0/bin/gcc strcpy strcat file_exists(buf) returns 0 15

Example: find_path( gcc )... NULL searchpaths "/opt/gnu/bin" "/home2/jdk1.5.0/bin" "/usr/ccs/bin" buf /opt/gnu/bin/gcc strcpy strcat file_exists(buf) returns 1 print /opt/gnu/bin/gcc 16