Session 3 4-Revision
Session 3 4-Revision
Session 3 4-Revision
Session 3 & 4
Revision
Session-3-Revision
parent: child=1234
child: exiting
I/O and File Descriptors
• A file descriptor is a small integer representing a
kernel-managed object that a process may read
from or write to.
• A process may obtain a file descriptor by opening
a file, directory, or device, or by creating a pipe, or
by duplicating an existing descriptor.
• By convention, a process reads from file
descriptor 0 (standard input), writes output to file
• descriptor 1 (standard output), and writes error
messages to file descriptor 2 (standard error).
read and write System Calls
• The read and write system calls read bytes from
and write bytes to open files named by file
descriptors.
• The call read(fd, buf, n) reads at most n bytes
from the file descriptor fd, copies them into buf,
and returns the number of bytes read.
• Each file descriptor that refers to a file has an
offset associated with it.
• The call write(fd, buf, n) writes n bytes from buf
to the file descriptor fd and returns the number
of bytes written.
To copy data from its standard input to its standard output
• #include”type.h”
• #include”stat.h”
• #include”user.h”
• int main(vod)
• {
• char buf[512];
• int n;
• for(;;){
• n = read(0, buf, sizeof buf);
• if(n == 0)
• break;
• if(n < 0){
• fprintf(2, "read error\n");
• exit();
• }
• if(write(1, buf, n) != n){
• fprintf(2, "write error\n");
• exit();
• }
• }
Review of Session-4