Introduction to Computer Systems

Download Report

Transcript Introduction to Computer Systems

System-Level I/O
1
Outline
•
•
•
•
I/O redirection
Robust I/O
Standard I/O
Suggested Reading
– 10.4, 10.7~10.9
2
I/O Redirection
• Question: How does a shell implement I/O redirection?
unix> ls > foo.txt
• Answer: By calling the dup2(oldfd, newfd) function
– Copies (per-process) descriptor table entry oldfd to entry
newfd
Descriptor table
before dup2(4,1)
fd 0
fd 1
fd 2
fd 3
fd 4
a
b
Descriptor table
after dup2(4,1)
fd 0
fd 1
fd 2
fd 3
fd 4
b
b
3
I/O Redirction
unix > ls > foo.txt
• dup2 copies entries in the per-process file descriptor
table.
#include <unistd.h>
int dup2(int oldfd, int newfd);
returns: nonnegative descriptor if OK,
-1 on error
• dup2(oldfd, newfd) overwrites the entry in the
per-process file table for newfd with the entry for
oldfd.
4
Redirection
dup2(4,1)
Descriptor table
(one table per
process)
fd0
fd1
fd2
fd3
fd4
fd5
fd6
fd7
open file table
(shared by all
process)
file A
V-node table
(shared by all
processes)
file pos
file A
File access
refcnt = 1
File size
...
File type
file B
…
file pos
file B
File access
refcnt = 1
File size
...
File type
…
5
Redirection
dup2(4,1)
Descriptor table
(one table per
process)
fd0
fd1
fd2
fd3
fd4
fd5
fd6
fd7
open file table
(shared by all
process)
file A
V-node table
(shared by all
processes)
file pos
file A
File access
refcnt = 0
File size
...
File type
file B
…
file pos
file B
File access
refcnt = 2
File size
...
File type
…
6
Redirection
#include “csapp.h”
foobar.txt
foobar
int main()
{
int fd1, fd2;
char c;
fd1 = open(“foobar.txt”, O_RDONLY, 0) ;
fd2 = open(“foobar.txt”, O_RDONLY, 0) ;
read(fd2, &c, 1) ;
dup2(fd2, fd1) ;
read(fd1, &c, 1) ;
printf(“c = %c\n”, c) ;
exit(0)
}
7
Fun with File Descriptors (1)
#include "csapp.h"
int main(int argc, char *argv[])
{
int fd1, fd2, fd3;
char c1, c2, c3;
char *fname = argv[1];
fd1 = Open(fname, O_RDONLY, 0);
fd2 = Open(fname, O_RDONLY, 0);
fd3 = Open(fname, O_RDONLY, 0);
Dup2(fd2, fd3);
Read(fd1, &c1, 1);
Read(fd2, &c2, 1);
Read(fd3, &c3, 1);
printf("c1 = %c, c2 = %c, c3 = %c\n", c1, c2, c3);
return 0;
ffiles1.c
}
• What would this program print for file
containing “abcde”?
8
Fun with File Descriptors (2)
#include "csapp.h"
int main(int argc, char *argv[])
{
int fd1;
int s = getpid() & 0x1;
char c1, c2;
char *fname = argv[1];
fd1 = Open(fname, O_RDONLY, 0);
Read(fd1, &c1, 1);
if (fork()) { /* Parent */
sleep(s);
Read(fd1, &c2, 1);
printf("Parent: c1 = %c, c2 = %c\n", c1, c2);
} else { /* Child */
sleep(1-s);
Read(fd1, &c2, 1);
printf("Child: c1 = %c, c2 = %c\n", c1, c2);
}
return 0;
ffiles2.c
}
• What would this program print for file
containing “abcde”?
9
Fun with File Descriptors (3)
#include "csapp.h"
int main(int argc, char *argv[])
{
int fd1, fd2, fd3;
char *fname = argv[1];
fd1 = Open(fname, O_CREAT|O_TRUNC|O_RDWR, S_IRUSR|S_IWUSR);
Write(fd1, "pqrs", 4);
fd3 = Open(fname, O_APPEND|O_WRONLY, 0);
Write(fd3, "jklmn", 5);
fd2 = dup(fd1); /* Allocates descriptor */
Write(fd2, "wxyz", 4);
Write(fd3, "ef", 2);
return 0;
ffiles3.c
}
• What would be the contents of the resulting
file?
10
The RIO Package
• RIO is a set of wrappers that provide efficient
and robust I/O in apps, such as network
programs that are subject to short counts
• RIO provides two different kinds of functions
– Unbuffered input and output of binary data
• rio_readn and rio_writen
– Buffered input of binary data and text lines
• rio_readlineb and rio_readnb
11
Unbuffered I/O
• Transfer data directly between memory and a file, with
no application-level buffering
#include "csapp.h"
ssize_t rio_readn(int fd, void *usrbuf, size_t count);
ssize_t rio_writen(int fd, void *usrbuf, size_t count);
return: number of bytes read (0 if EOF) or written,
-1 on error
•
•
•
•
rio_readn returns short count only if it encounters EOF
Only use it when you know how many bytes to read
rio_writen never returns a short count
Calls to rio_readn and rio_writen can be interleaved arbitrarily on
the same descriptor
12
1 ssize_t rio_readn(int fd, void *buf, size_t count)
2 {
3
size_t nleft = count;
4
ssize_t nread;
5
char *ptr = buf;
6
7
while (nleft > 0) {
8
if ((nread = read(fd, ptr, nleft)) < 0) {
9
if (errno == EINTR)
10
nread = 0; /* and call read() again */
11
else
12
return -1; /* errno set by read() */
13
}
14
else if (nread == 0)
15
break; /* EOF */
16
nleft -= nread;
17
ptr += nread;
18
}
19
return (count - nleft); /* return >= 0 */
20 }
13
1 ssize_t rio_writen(int fd, const void *buf, size_t count)
2 {
3
size_t nleft = count;
4
ssize_t nwritten;
5
const char *ptr = buf;
6
7
while (nleft > 0) {
8
if ((nwritten = write(fd, ptr, nleft)) <= 0) {
9
if (errno == EINTR)
10
nwritten = 0; /* and call write() again */
11
else
12
return -1; /* errorno set by write() */
13
}
14
nleft -= nwritten;
15
ptr += nwritten;
16
}
17
return count;
18 }
14
Buffered I/O: Motivation
• Applications often read/write one character
at a time
– getc, putc, ungetc
– gets, fgets
• Read line of text on character at a time, stopping at
newline
• Implementing as Unix I/O calls expensive
– read and write require Unix kernel calls
• > 10,000 clock cycles
15
Buffered I/O: Motivation
• Solution: Buffered read
– Use Unix read to grab block of bytes
– User input functions take one byte at a time from
buffer
• Refill buffer when empty
Buffer already read
unread
16
Buffered I/O: Implementation
• For reading from file
• File has associated buffer to hold bytes that
have been read from file but not yet read by
user code
rio_cnt
Buffer already read
rio_buf
unread
rio_bufptr
typedef struct {
int rio_fd;
int rio_cnt;
char *rio_bufptr;
char rio_buf[RIO_BUFSIZE];
} rio_t;
/*
/*
/*
/*
descriptor for this internal buf */
unread bytes in internal buf */
next unread byte in internal buf */
internal buffer */
17
Buffered I/O: Implementation
• Layered on Unix file:
Buffered Portion
not in buffer
already read
unread
unseen
Current File Position
18
Buffered RIO Input Function
• Efficiently read text lines and binary data from a file
whose contents are cached in an application-level buffer
#include "csapp.h"
void rio_readinitb(rio_t *rp, int fd) ;
ssize_t rio_readlineb(rio_t *rp, void *usrbuf, size t maxlen);
returns: number of bytes read (0 if EOF), -1 on error
• rio_readlineb reads a text line of up to maxlen
bytes from file fd and stores the line in usrbuf
 Especially useful for reading text lines from network sockets
• Stopping conditions
 maxlen bytes read
 EOF encountered
 Newline (‘\n’) encountered
19
Buffered RIO Input Functions (cont)
#include "csapp.h"
void rio_readinitb(rio_t *rp, int fd);
ssize_t rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen);
ssize_t rio_readnb(rio_t *rp, void *usrbuf, size_t n);
Return: num. bytes read if OK, 0 on EOF, -1 on error
• rio_readnb reads up to n bytes from file fd
• Stopping conditions
 maxlen bytes read
 EOF encountered
• Calls to rio_readlineb and rio_readnb can be
interleaved arbitrarily on the same descriptor
 Warning: Don’t interleave with calls to rio_readn
20
Robust I/O
#define RIO_BUFSIZE 8192
typedef struct {
int rio_fd;
int rio_cnt;
char *rio_bufptr;
char rio_buf[RIO_BUFSIZE];
} rio_t ;
void rio_readinitb(rio_t *rp, int fd)
{
rp->rio_fd = fd ;
rp->rio_cnt = 0 ;
rp->rio_bufptr = rio_buf ;
}
21
Robust I/O
#include “csapp.h”
int main(int argc, char **argv)
{
int n;
rio_t rio;
char buf[MAXLINE];
Rio_readinitb(&rio, STDIN_FILENO);
while ((n = Rio_readlineb(
&rio, buf, MAXLINE) ) != 0 )
Rio_writen(STDOUT_FILENO, buf, n);
}
22
1 static ssize_t rio_read(rio_t *rp, char *usrbuf, size_t n)
2 {
3
int cnt = 0;
4
5
while (rp->rio_cnt <= 0) { /* refill if buf is empty */
6
rp->rio_cnt = read(rp->rio_fd, rp->rio_buf,
7
sizeof(rp->rio_buf));
8
if ( rp->rio_cnt < 0) {
9
if (errno != EINTR)
10
return –1 ;
11
}
12
else if (rp->rio_cnt == 0) /* EOF */
13
return 0;
14
else
15
rp->rio_bufptr = rp->rio_buf;/* reset buffer ptr */
16
}
17
23
18
19
20
21
22
23
24
25
26 }
/* Copy min(n, rp->rio_cnt) bytes
from internal buf to user buf */
cnt = n ;
if ( rp->rio_cnt < n)
cnt = rp->rio_cnt ;
memcpy(usrbuf, rp->rio_bufptr, cnt) ;
rp->rio_buffer += cnt ;
rp->rio_cnt -= cnt ;
return cnt ;
24
1 ssize_t rio_readnb(rio_t *rp, void *usrbuf, size_t n)
2 {
3
size_t nleft = n;
ssize_t nread ;
4
char *bufp = usrbuf;
5
while (nleft > 0) {
6
if ((nread = rio_read(rp, bufp, nleft)) < 0) {
7
if ( errno = EINTR)
8
/* interrupted by sig handler return */
9
nread = 0;
10
else
11
return –1;
12
}
13
else if (nread == 0)
14
break;
15
nleft -= nread;
16
bufp += nread;
17
}
18
return (n – nleft);
25
19 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
ssize_t rio_readlineb (rio_t *rp,
void *usrbuf, size_t maxlen)
{
int n, rc;
char c, *bufp = usrbuf;
for (n=1; n < maxlen; n++) {
if ((rc = rio_read(rp, &c, 1)) == 1) {
*bufp++ = c;
if (c == ‘\n’)
break;
} else if (rc == 0) {
if (n== 1)
return 0; /* EOF, no data read */
else
break;
} else
return –1; /* error */
}
*bufp = 0 ;
return n ;
}
26
Standard I/O
• The C standard library (libc.so) contains
a collection of higher-level standard I/O
functions
• 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)
27
Standard I/O
• Standard I/O models open files as streams
– Abstraction for a file descriptor and a buffer in
memory.
– Similar to buffered RIO
• C programs begin life with three open streams
(defined in stdio.h)
– stdin (standard input fd=0)
– stdout (standard output fd=1)
– stderr (standard error fd=2)
28
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);
• Buffer flushed to output fd on “\n” or fflush() call
29
Standard I/O Buffering in Action
• You can see this buffering in action for
yourself, using the always fascinating Unix
strace program:
#include <stdio.h>
int main()
{
printf("h");
printf("e");
printf("l");
printf("l");
printf("o");
printf("\n");
fflush(stdout);
exit(0);
}
linux> strace ./hello
execve("./hello", ["hello"], [/* ... */]).
...
write(1, "hello\n", 6)
= 6
...
exit_group(0)
= ?
30
Unix I/O, Standard I/O, and Robust I/O
• Standard I/O and RIO are implemented using lowlevel Unix I/O
fopen
fread
fscanf
sscanf
fgets
fflush
fclose
fdopen
fwrite
fprintf
sprintf
fputs
fseek
open
write
stat
read
lseek
close
C application program
Standard I/O
functions
RIO
functions
Unix I/O functions
(accessed via system calls)
• Which ones should you use in your programs?
rio_readn
rio_writen
rio_readinitb
rio_readlineb
rio_readnb
31
Pros and Cons of Unix I/O
• Pros
– Unix I/O is the most general and lowest overhead
form of I/O.
• All other I/O packages are implemented using Unix I/O
functions.
– Unix I/O provides functions for accessing file
metadata.
– Unix I/O functions are async-signal-safe and can
be used safely in signal handlers.
32
Pros and Cons of Unix I/O
• Cons
– Dealing with short counts is tricky and error prone.
– Efficient reading of text lines requires some form of
buffering, also tricky and error prone.
– Both of these issues are addressed by the standard
I/O and RIO packages.
33
Pros and Cons of Standard I/O
• Pros:
– Buffering increases efficiency by decreasing the
number of read and write system calls
– Short counts are handled automatically
34
Pros and Cons of Standard I/O
• Cons:
– Provides no function for accessing file metadata
– Standard I/O functions are not async-signal-safe,
and not appropriate for signal handlers.
– Standard I/O is not appropriate for input and
output on network sockets
• There are poorly documented restrictions on streams that
interact badly with restrictions on sockets (Sec 10.9)
35
Choosing I/O Functions
• General rule: use the highest-level I/O
functions you can
– Many C programmers are able to do all of their work
using the standard I/O functions
36
Choosing I/O Functions
• When to use standard I/O
– When working with disk or terminal files
• When to use raw Unix I/O
– Inside signal handlers, because Unix I/O is asyncsignal-safe.
– In rare cases when you need absolute highest
performance.
• When to use RIO
– When you are reading and writing network sockets.
– Avoid using standard I/O on sockets.
37
Aside: Working with Binary Files
• Binary File Examples
– Object code, Images (JPEG, GIF),
• Functions you shouldn’t use on binary files
– Line-oriented I/O such as fgets, scanf,
printf, rio_readlineb
• Different systems interpret 0x0A (‘\n’) (newline)
differently:
– Linux and Mac OS X: LF(0x0a) [‘\n’]
– HTTP servers & Windoes: CR+LF(0x0d 0x0a)
[‘\r\n’]
• Use rio_readn or rio_readnb instead
– String functions
• strlen, strcpy
• Interprets byte value 0 (end of string) as special
38
For Further Information
• The Unix bible:
– W. Richard Stevens & Stephen A. Rago, Advanced Programming
in the Unix Environment, 2nd Edition, Addison Wesley, 2005
• Updated from Stevens’s 1993 classic text.
• Stevens is arguably the best technical writer ever.
– Produced authoritative works in:
•
•
•
•
Unix programming
TCP/IP (the protocol that makes the Internet work)
Unix network programming
Unix IPC programming
• Tragically, Stevens died Sept. 1, 1999
– But others have taken up his legacy
39
Next
• Network Programming
40