Contents. NOTICE & Programming Assignment 0 review. What will be next project? File IO & File IO exercise

Similar documents
File I/O. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.

Contents. Programming Assignment 0 review & NOTICE. File IO & File IO exercise. What will be next project?

File I/O. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

All the scoring jobs will be done by script

All the scoring jobs will be done by script

Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University

Contents. NOTICE & Programming Assignment #1. QnA about last exercise. File IO exercise

System-Level I/O. Topics Unix I/O Robust reading and writing Reading file metadata Sharing files I/O redirection Standard I/O

System-Level I/O Nov 14, 2002

A Typical Hardware System The course that gives CMU its Zip! System-Level I/O Nov 14, 2002

System- Level I/O. Andrew Case. Slides adapted from Jinyang Li, Randy Bryant and Dave O Hallaron

Lecture 23: System-Level I/O

System-Level I/O March 31, 2005

The course that gives CMU its Zip! I/O Nov 15, 2001

CS 201. Files and I/O. Gerson Robboy Portland State University

System- Level I/O. CS 485 Systems Programming Fall Instructor: James Griffioen

Introduction to Computer Systems , fall th Lecture, Oct. 19 th

System-Level I/O. William J. Taffe Plymouth State University. Using the Slides of Randall E. Bryant Carnegie Mellon University

File Input and Output (I/O)

Unix programming interface for file I/O operations and pipes

UNIX I/O. Computer Systems: A Programmer's Perspective, Randal E. Bryant and David R. O'Hallaron Prentice Hall, 3 rd edition, 2016, Chapter 10

System-Level I/O April 6, 2006

System-Level I/O : Introduction to Computer Systems 16 th Lecture, March 23, Instructors: Franz Franchetti & Seth Copen Goldstein

Important Dates. October 27 th Homework 2 Due. October 29 th Midterm

Foundations of Computer Systems

System- Level I/O /18-243: Introduc3on to Computer Systems 16 th Lecture, Mar. 15, Instructors: Gregory Kesden and Anthony Rowe

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo

Operating System Labs. Yuanbin Wu

I/O OPERATIONS. UNIX Programming 2014 Fall by Euiseong Seo

structs as arguments

UNIX System Calls. Sys Calls versus Library Func

Memory Mapped I/O. Michael Jantz. Prasad Kulkarni. EECS 678 Memory Mapped I/O Lab 1

CSC 271 Software I: Utilities and Internals

Operating System Labs. Yuanbin Wu

Contents. PA1 review and introduction to PA2. IPC (Inter-Process Communication) Exercise. I/O redirection Pipes FIFOs

Contents. IPC (Inter-Process Communication) Representation of open files in kernel I/O redirection Anonymous Pipe Named Pipe (FIFO)

Files and Directories Filesystems from a user s perspective

File System (FS) Highlights

File Systems. q Files and directories q Sharing and protection q File & directory implementation

CS , Spring Sample Exam 3

File Systems. Today. Next. Files and directories File & directory implementation Sharing and protection. File system management & examples

which maintain a name to inode mapping which is convenient for people to use. All le objects are

UNIX System Programming

System Calls and I/O Appendix. Copyright : University of Illinois CS 241 Staff 1

17: Filesystem Examples: CD-ROM, MS-DOS, Unix

Outline. OS Interface to Devices. System Input/Output. CSCI 4061 Introduction to Operating Systems. System I/O and Files. Instructor: Abhishek Chandra

Operating System Labs. Yuanbin Wu

What Is Operating System? Operating Systems, System Calls, and Buffered I/O. Academic Computers in 1983 and Operating System

Design Choices 2 / 29

CS240: Programming in C

CSci 4061 Introduction to Operating Systems. File Systems: Basics

Advanced Systems Security: Ordinary Operating Systems

39. File and Directories

UNIX input and output

System Calls. Library Functions Vs. System Calls. Library Functions Vs. System Calls

CSE 333 SECTION 3. POSIX I/O Functions

CSE 410: Systems Programming

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

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

Pipes and FIFOs. Woo-Yeong Jeong Computer Systems Laboratory Sungkyunkwan University

Automated Test Generation in System-Level

The link() System Call. Preview. The link() System Call. The link() System Call. The unlink() System Call 9/25/2017

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

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Chapter 4 - Files and Directories. Information about files and directories Management of files and directories

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Naked C Lecture 6. File Operations and System Calls

ELEC-C7310 Sovellusohjelmointi Lecture 3: Filesystem

Preview. System Call. System Call. System Call. System Call. Library Functions 9/20/2018. System Call

CS631 - Advanced Programming in the UNIX Environment

CSI 402 Lecture 2 Working with Files (Text and Binary)

Lecture 8: Structs & File I/O

Unix File and I/O. Outline. Storing Information. File Systems. (USP Chapters 4 and 5) Instructor: Dr. Tongping Liu

Introduction to Linux

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

System Software Experiment 1 Lecture 7

Master Calcul Scientifique - Mise à niveau en Informatique Written exam : 3 hours

OPERATING SYSTEMS: Lesson 2: Operating System Services

Goals of this Lecture

PROGRAMMAZIONE I A.A. 2017/2018

I/O Management! Goals of this Lecture!

Introduction to Linux

I/O Management! Goals of this Lecture!

Logistics. Recitation 11: I/O Problems. Today s Plan. Why Use Robust I/O. Andrew Faulring Section A 18 November 2002

ENG120. Misc. Topics

Thesis, antithesis, synthesis

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Lecture 7: file I/O, more Unix

Computer Science & Engineering Department I. I. T. Kharagpur

CSE 333 SECTION 3. POSIX I/O Functions

INTRODUCTION TO UNIX FILE SYSTEM:

Standard C Library Functions

Process Management! Goals of this Lecture!

System Calls and I/O. CS 241 January 27, Copyright : University of Illinois CS 241 Staff 1

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Input / Output Functions

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

Linux Forensics. Newbug Tseng Oct

everything is a file main.c a.out /dev/sda1 /dev/tty2 /proc/cpuinfo file descriptor int

Systems Programming. COSC Software Tools. Systems Programming. High-Level vs. Low-Level. High-Level vs. Low-Level.

Transcription:

File I/O Prof. Jin-Soo Kim( jinsookim@skku.edu) TA Dong-Yun Lee(dylee@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu

Contents NOTICE & Programming Assignment 0 review What will be next project? File IO & File IO exercise 2

Notice (1) We will use grading server, not e-mail swe2007.2016@gmail.com is just for questions PA #1 will be uploaded in a few days 3

sys Server Guide (1) 1. Go to the csl sys server http://sys.skku.edu/ 4

sys Server Guide (2) 2. Press Join and type your personal info your e-mail addr passwd KOREAN name anything you want 학번 5

sys Server Guide (3) 3. Wait for a while, and check TA session check and press Submit 6

sys Server Guide (4) 4. Assignments tab is for uploading your jobs View details : document for PA Template Code : skeleton files will be uploaded in.tar.gz Submit & Test : Submit and Test! 7

sys Server Guide (5) 5. There are some strict rules for uploading Your Source Code should be in a strict format Detailed formatting rules will be announced in a Documents Your Report should be.pdf There is no restriction in your report, but there is a restriction in format 6. After uploading your codes, press Run to make your codes run 7. Wait 8

sys Server Guide (6) Check your PA #0 scores with sys server right now! 9

Notice (2) Delay : -20 % per a day No report for PA #0 From PA #1, you should submit report as well 10

PA #0 Review (1) What is difference between char str[10] = hello ; char *str = hello ; malloc? calloc? Kernel? 11

PA #0 Review (2) Why there are two types of files?.h header file.c C codes Divide interface and implementation Actually, you don t have to know about detailed impl ementation when using system call 12

PA #0 Review (3) const qualifier void foo1(const char *s1) { s1[0] = a ; void foo2(const char *s1) { s1 = hey ; void foo3(const char *s1) { char *s = s1; void foo4(const char *s1) { char *s = s1; s[0] = e ; void foo5 (char * const s1) { s1[0] = a ; void foo6(char * const s1) { s1 = hey ; 13

PA #0 Review - C Any question about PA #0? 14

Unix Files Unix : Everything is a file Even there is a wiki-page named Everything is a file A Unix file is a sequence of m bytes: B 0, B 1,..., B k,..., B m-1 All I/O devices are represented as files: /dev/sda1 (disk partition) /dev/tty2 (terminal) Even the kernel is represented as a file: /dev/kmem (kernel memory image) /proc /sys (kernel data structures, proc file system) (kernel data structures, sys file system) 15

Unix File Types Regular file Binary or text file Unix does not know the difference! (.out vs..txt) Directory file A file that contains the names and locations of other files. Character special and block special files Terminals (character special) and disks (block special) FIFO (named pipe) A file type used for inter-process communication Socket A file type used for network communication between processes 16

Unix I/O Q. How can we communicate with file? A. Unix file I/O Characteristics The elegant mapping of files to devices allows kernel to export simple interface called Unix I/O. All input and output is handled in a consistent and uniform way Basic Unix I/O operations (system calls): Opening and closing files 1. open() and 2. close() Reading and writing a file 3. read() and 4. write() Changing the current file position(offset) (seek) 5. lseek() 17

Opening Files Opening a file informs the kernel that you are getting ready to access that file. int fd; /* file descriptor */ if ((fd = open("/etc/hosts", O_RDONLY)) < 0) { perror("open"); exit(1); Returns a small identifying integer file descriptor fd == -1 indicates that an error occurred Each process created by a Unix shell begins life with three open files associated with a terminal: 0: standard input 1: standard output 2: standard error 18

Closing Files Closing a file informs the kernel that you are finished accessing that file. int fd; /* file descriptor */ int retval; /* return value */ if ((retval = close(fd)) < 0) { perror("close"); exit(1); Closing an already closed file is a recipe for disaster in threaded programs (more on this later) Moral: Always check return codes, even for seemingly benign functions such as close() 19

Reading Files Reading a file copies bytes from the current file position to memory, and then updates file position. char buf[512]; int fd; /* file descriptor */ int nbytes; /* number of bytes read */ /* Open file fd... */ /* Then read up to 512 bytes from file fd */ if ((nbytes = read(fd, buf, sizeof(buf))) < 0) { perror("read"); exit(1); Returns number of bytes read from file fd into buf nbytes < 0 indicates that an error occurred. short counts (nbytes < sizeof(buf)) are possible and are not errors! 20

Writing Files Writing a file copies bytes from memory to the current file position, and then updates current file position. char buf[512]; int fd; /* file descriptor */ int nbytes; /* number of bytes read */ /* Open the file fd... */ /* Then write up to 512 bytes from buf to file fd */ if ((nbytes = write(fd, buf, sizeof(buf)) < 0) { perror("write"); exit(1); Returns number of bytes written from buf to file fd. nbytes < 0 indicates that an error occurred. As with reads, short counts are possible and are not errors! 21

Dealing with Short Counts Short counts can occur in these situations: Encountering (end-of-file) EOF on reads. Reading text lines from a terminal. Reading and writing network sockets or Unix pipes. Short counts does not occur in these situations: Reading from disk files (except for EOF) Writing to disk files. How should you deal with short counts in your code? One way is to use the RIO (Robust I/O) package from your textbook s csapp.c file (Appendix B). Or using loop.. 22

File Offset An offset of an opened file can be set explicitly by calling lseek(), lseek64() char buf[512]; int fd; /* file descriptor */ off_t pos; /* file offset */ /* Get current file offset */ pos = lseek(fd, 0, SEEK_CUR); /* The file offset is incremented by written bytes */ write(fd, buf, sizeof(buf)); /* Set file position to the first byte of the file */ pos = lseek(fd, 0, SEEK_SET); Returns the new offset of the file fd. nbytes < 0 indicates that an error occurred. An offset can be set beyond the end of the file. If data is written at that point, a file hole is created. 23

Unix I/O Example Copying standard input to standard output one byte at a time. int main(void) { char c; while(read(0, &c, 1)!= 0) write(1, &c, 1); exit(0); Is that work? 24

Standard I/O Functions The C standard library (libc.a) contains a collection of higher-level standard I/O functions Documented in Appendix B of K&R. Examples of standard I/O functions: Opening and closing files (fopen and fclose) Reading and writing bytes (fread and fwrite) Reading and writing text lines (fgets and fputs) Formatted reading and writing (fscanf and fprintf) 25

Standard I/O Streams Standard I/O models open files as streams Abstraction for a file descriptor and a buffer in memory C programs begin life with three open streams (defined in stdio.h) stdin (standard input) stdout (standard output) stderr (standard error) #include <stdio.h> extern FILE *stdin; /* standard input (descriptor 0) */ extern FILE *stdout; /* standard output (descriptor 1) */ extern FILE *stderr; /* standard error (descriptor 2) */ int main() { fprintf(stdout, "Hello, world\n"); 26

Buffering in Standard I/O Standard I/O functions use buffered I/O buf printf("h"); printf("e"); printf("l"); printf("l"); printf("o"); printf("\n"); h e l l o \n.. fflush(stdout); write(1, buf += 6, 6); 27

Unix I/O vs. Standard I/O Standard I/O are implemented using low-level Unix I/O. fopen fread fscanf sscanf fgets fflush fclose fdopen fwrite fprintf sprint fputs fseek Standard I/O functions C application program RIO functions rio_readn rio_written rio_readinitb rio_readlineb rio_readnb open read write lseek stat close Unix I/O functions (accessed via system calls) Which ones should you use in your programs? 28

Pros/Cons of Unix I/O Pros The most general and lowest overhead form of I/O All other I/O packages are implemented on top of Unix I/O functions Unix I/O provides functions for accessing file metadata Cons System call overheads for small-sized I/O Dealing with short counts is tricky and error prone Efficient reading of text lines requires some form of buffering, also tricky and error prone These issues are addressed by the standard I/O 29

Pros/Cons of Standard I/O Pros Buffuring increases efficiency by decreasing the number of read() and write() system calls. Shout counts are handled automatically. Cons Provides no function for accessing file metadata. Standard I/O is not appropriate for input and output on network sockets. But there is a way using fdopen() 30

Summary Unix file I/O open(), read(), write(), close(),... A uniform way to access files, I/O devices, network sockets, kernel data structures, etc When to use standard I/O? When working with disk or terminal files When to use raw Unix I/O When you need to fetch file metadata When you read or write network sockets or pipes In rare cases when you need absolute highest performance 31

Exercise (1) Lab exercise #1: Let s make xcat, xcp utilities. xcat prints a file on the standard output. xcp copies contents of a file into a new file. Basically, executing xcat and xcp will be same as executing cat and cp without any options, respectively. Your job is to make xcat and xcp by using system calls provided by Linux. 32

Exercise (2) Run? Warning? Error? + explain it corretly void foo1(const char *s1) { s1[0] = a ; void foo2(const char *s1) { s1 = hey ; void foo3(const char *s1) { char *s = s1; void foo4(const char *s1) { char *s = s1; s[0] = e ; void foo5 (char * const s1) { s1[0] = a ; void foo6(char * const s1) { s1 = hey ; 33

Exercise (3) Why below code do not work correctly? Explain it correctly You can use anything for the answer int main(void) { char c; while(read(0, &c, 1)!= 0) write(1, &c, 1); exit(0); 34

File Metadata Data about data, in this case file data. Maintained by kernel, accessed by users with the stat and fstat functions. /* Metadata returned by the stat and fstat functions */ struct stat { dev_t st_dev; /* device */ ino_t st_ino; /* inode */ mode_t st_mode; /* protection and file type */ nlink_t st_nlink; /* number of hard links */ uid_t st_uid; /* user ID of owner */ gid_t st_gid; /* group ID of owner */ dev_t st_rdev; /* device type (if inode device) */ off_t st_size; /* total size, in bytes */ unsigned long st_blksize; /* blocksize for filesystem I/O */ unsigned long st_blocks; /* number of blocks allocated */ time_t st_atime; /* time of last file access */ time_t st_mtime; /* time of last file modification */ time_t st_ctime; /* time of last inode change */ ; /* statbuf.h included by sys/stat.h */ 35

Accessing File Metadata /* statcheck.c - Querying and manipulating a file s meta data */ int main (int argc, char **argv) { struct stat st; char *type, *readok; stat(argv[1], &st); if (S_ISREG(st.st_mode)) /* file type */ type = "regular"; else if (S_ISDIR(st.st_mode)) type = "directory"; else type = "other"; if ((st.st_mode & S_IRUSR)) /* OK to read? */ readok = "yes"; else readok = "no"; bass>./statcheck statcheck.c type: regular, read: yes bass> chmod 000 statcheck.c bass>./statcheck statcheck.c type: regular, read: no printf("type: %s, read: %s\n", type, readok); exit(0); 36