SlideShare a Scribd company logo
1 of 8
Download to read offline
Copyright ©1997 Computer Science 217: Operating System Page 187
November 2, 1999
Operating Systems
• Operating systems manage processes and resources
• Processes are executing instances of programs
• State vector: registers, program counter, memory mgmt registers, etc.
code
data
SV
process 3
code
data
SV
process 1
code
data
SV
process 2
state vector: information necessary to start, stop, and restart the process
may be the same or different programs
user-level processes
operating system, “kernel”
bare machine
assembly & high-level languages
machine language & system calls
machine language
Copyright ©1997 Computer Science 217: Operating System Page 188
November 2, 1999
Privileged Instructions
• Machines have two kinds of instructions
1. “normal” instructions, e.g., add, sub, etc.
2. “privileged” instructions, e.g.,
initiate I/O
switch state vectors or contexts
load/save from protected memory
etc.
• Operating systems hide privileged instructions and provide virtual
instructions to access and manipulate virtual resources, e.g., I/O to and
from disc files
• Virtual instructions are system calls
• Operating systems interpret virtual instructions
Copyright ©1997 Computer Science 217: Operating System Page 189
November 2, 1999
Processor Modes
• Machine level typically has 2 modes, e.g., “user” mode and “kernel”
mode
• User mode
processor executes “normal” instructions in the user’s program
upon encountering a “privileged” instruction, processor switches to kernel mode, and
the operating system performs a service
• Kernel mode
processor executes both normal and privileged instructions
• User-to-kernel switch saves the information necessary to continue the
execution of the user process
• Another view
Operating system is a process that runs in kernel mode.
Copyright ©1997 Computer Science 217: Operating System Page 190
November 2, 1999
Virtual Resources
• OS provides a high-level representation of low-level resources
• For example, low-level disks are presented as file systems
simple to use file system
tree-structured, hierarchical
directories
named files
files are sequences of bytes
network
k disk drives
different capacities, speeds
access via cylinder, sector, track
fixed I/O format and transfer rules
authentication
error correction and handling
UNIX Operating System
Copyright ©1997 Computer Science 217: Operating System Page 191
November 2, 1999
System Calls
• Virtual instructions are often presented as a set of system calls
• Typical implementations (in order of prevalence)
single privileged instruction with parameters
interpret to other privileged instructions
jump to fixed locations
• Parameters are passed in a machine-dependent manner
in fixed registers
in fixed memory locations
in an argument block, with the block’s address in a register
in-line with the system call
on the stack
combination of the above
• System calls return results in registers, memory, etc., and an error
indication
Copyright ©1997 Computer Science 217: Operating System Page 192
November 2, 1999
System Calls, cont’d
• System call mechanism is tailored to the machine architecture
system calls on the SPARC use a trap instruction
ta 0
trap always; a trap value of 0 indicates a system call
parameters are in registers %g1, %o0 — %o5 and on the stack
• System call interface often designed to accommodate high-level
languages
system calls are accessed by a library of procedures
e.g., on UNIX, system calls are packaged as a library of C functions
• Typical UNIX system call
nread = read(fd, buffer, n);
returns the number of bytes read from the file fd, or -1 if an error occurs
what about EOF?
Copyright ©1997 Computer Science 217: Operating System Page 193
November 2, 1999
Implementing System Calls as Functions
• In the caller
mov fd,%o0
mov buffer,%o1
mov n,%o2
call _read; nop
mov %o0,nread
• Implementation of read
_read:
set 3,%g1 /* 3 indicates READ system call */
ta 0
bcc L1; nop
set _errno,%g1 /* sets errno to the error code */
st %o0,[%g1]
set -1,%o0 /* return -1 to indicate an error */
L1: retl; nop
operating system
sets the C bit if an error occurred
stores an error code in %o0; see /usr/include/sys/errno.h
note that read is a leaf function
• UNIX has ~150 system calls
see “man 2 intro” and /usr/include/syscall.h
Copyright ©1997 Computer Science 217: Operating System Page 194
November 2, 1999
Exceptions and Interrupts
• Operating systems also field exceptions and interrupts
• Exceptions (a.k.a. traps): caused by execution of an instruction
e.g., divide by 0, illegal address, memory protection violation, illegal opcode
• Exceptions are like implicit system calls
operating systems can pass control to user processes to handle exceptions (e.g.,
“signals”)
operating systems have ways to process exceptions by defaults
e.g., segmentation fault and core dump
• Interrupts: caused by “external” activity unrelated to the user process
e.g., I/O completion, clock tick, etc.
• Interrupts are like transparent system calls
normally user processes cannot detect interrupts, nor need to deal with them
Copyright ©1997 Computer Science 217: Operating System Page 195
November 2, 1999
SPARC Traps
• A trap instruction
enters kernel mode
disables other traps
decrements CWP
saves PC, nPC in %r17, %r18
sets PC to TBR, nPC to TBR + 4
• Hardware trap codes
1 reset
2 access exception
3 illegal instruction
...
• Software trap codes
sets TBR to trap number + 128
• There are conditional traps just like conditional branches
• There are separate floating point traps
Copyright ©1997 Computer Science 217: Operating System Page 196
November 2, 1999
System Calls for Input/Output
• Associating/disassociating files with file descriptors
int open(char *filename, int flags, int mode)
int close(int fd)
• Reading/writing from file descriptors
int read(int fd, char *buf, int nbytes)
int write(int fd, char *buf, int nbytes)
• Another version of cp source destination (see src/cp1.c)
#include <sys/file.h>
main(int argc, char *argv[]) {
int count, src, dst;
char buf[4096];
if (argc != 3)
error("usage: %s source destinationn", argv[0]);
if ((src = open(argv[1], O_RDONLY, 0)) < 0)
error("%s: can’t read ‘%s’n", argv[0], argv[1]);
if ((dst = open(argv[2], O_WRONLY|O_CREAT, 0666)) < 0)
error("%s: can’t write ‘%s’n", argv[0], argv[2]);
while ((count = read(src, buf, sizeof buf)) > 0)
write(dst, buf, count);
return EXIT_SUCCESS;
}
Copyright ©1997 Computer Science 217: Operating System Page 197
November 2, 1999
Write with Confidence
• Most programs don’t check for write errors or writes that are too large
int ironclad_write(int fd, char *buf, int nbytes) {
char *p, *q;
int n;
p = buf;
q = buf + nbytes;
while (p < q)
if ((n = write(fd, p, q - p)) > 0)
p += n;
else
perror("iconclad_write:");
return nbytes;
}
• perror issues a diagnostic for the error code in errno
iconclad_write: file system full
Copyright ©1997 Computer Science 217: Operating System Page 198
November 2, 1999
Buffered I/O
• Single-character I/O is usually too slow
int getchar(void) {
char c;
if (read(0, &c, 1) == 1)
return c;
return EOF;
}
• Solution: read chunks of input into a buffer, dole out chars one at a time
int getchar(void) {
static char buf[1024];
static char *p;
static int n = 0;
if (n--)
return *p++;
if ((n = read(0, p = buf, sizeof buf)) > 0)
return getchar();
n = 0;
return EOF;
}
• Where’s the bug?
Copyright ©1997 Computer Science 217: Operating System Page 199
November 2, 1999
Implementing the Standard I/O Library
• Single-character I/O functions are usually implemented as macros
#define getc(p) (--(p)->_cnt >= 0 ? 
(int)(*(unsigned char *)(p)->_ptr++) : 
_filbuf(p))
#define getchar() (getc(stdin))
• A FILE holds per-file buffer information
typedef struct _iobuf {
int _cnt; /* number of characters/slots left in the
buffer */
char *_ptr; /* pointer to the next character in the
buffer */
char *_base; /* the beginning of the buffer */
int _bufsiz; /* size of the buffer */
short _flag; /* open mode flags, etc. */
char _file; /* associated file descriptor */
} FILE;
extern FILE *stdin, *stdout, *stderr;
• See /usr/princeton/include/ansi/stdio.h
Copyright ©1997 Computer Science 217: Operating System Page 200
November 2, 1999
Buffered Writes
• Single-character writes are usually implemented by macros
#define putc(c,p) (--(p)->_cnt >= 0 ? 
(p)->_ptr++ = (c) : 
_flsbuf((c), (p)))
#define putchar(c) (putc((c),stdout))
• Buffering can interfere with interactive streams
for (p = "Enter your name:n"; *p; p++) putchar(*p);
for (p = buf; ; p++)
if ((*p = getchar()) == 'n')
break;
for (p = "Enter your age:n"; *p; p++) putchar(*p);
for (p = buf; ; p++)
if ((*p = getchar()) == 'n')
break;
bug: program waits for input before prompt appears
Copyright ©1997 Computer Science 217: Operating System Page 201
November 2, 1999
Buffered Writes, cont’d
• Output stream must be flushed before reading the input
void fflush(FILE *stream)
for (p = "Enter your name:n"; *p; p++) putchar(*p);
fflush(stdout);
for (p = buf; ; p++)
if ((*p = getchar()) == 'n')
break;
for (p = "Enter your age:n"; *p; p++) putchar(*p);
fflush(stdout);
for (p = buf; ; p++)
if ((*p = getchar()) == 'n')
break;
• Standard I/O supports line-buffered files
#define putc(x, p) (--(p)->_cnt >= 0 ?
(int)(*(unsigned char *)(p)->_ptr++ = (x)) : 
(((p)->_flag&_IOLBF) && -(p)->_cnt < (p)->_bufsiz ? 
((*(p)->_ptr = (x)) != 'n' ? 
(int)(*(unsigned char *)(p)->_ptr++) : 
_flsbuf(*(unsigned char *)(p)->_ptr, p)) : 
_flsbuf((unsigned char)(x), p)))
• Why is line buffering necessary?
f = fopen("/dev/tty", "w")

More Related Content

What's hot

Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O YourHelper1
 
Terminals and Shells
Terminals and ShellsTerminals and Shells
Terminals and ShellsHoffman Lab
 
Linux System Programming - Advanced File I/O
Linux System Programming - Advanced File I/OLinux System Programming - Advanced File I/O
Linux System Programming - Advanced File I/OYourHelper1
 
Linux System Programming - File I/O
Linux System Programming - File I/O Linux System Programming - File I/O
Linux System Programming - File I/O YourHelper1
 
LCU14 302- How to port OP-TEE to another platform
LCU14 302- How to port OP-TEE to another platformLCU14 302- How to port OP-TEE to another platform
LCU14 302- How to port OP-TEE to another platformLinaro
 
Central Processing Unit User View
Central Processing Unit User ViewCentral Processing Unit User View
Central Processing Unit User ViewAnuj Modi
 
Unix system programming
Unix system programmingUnix system programming
Unix system programmingSyed Mustafa
 

What's hot (8)

Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O
 
Terminals and Shells
Terminals and ShellsTerminals and Shells
Terminals and Shells
 
Embedded Android : System Development - Part III (Audio / Video HAL)
Embedded Android : System Development - Part III (Audio / Video HAL)Embedded Android : System Development - Part III (Audio / Video HAL)
Embedded Android : System Development - Part III (Audio / Video HAL)
 
Linux System Programming - Advanced File I/O
Linux System Programming - Advanced File I/OLinux System Programming - Advanced File I/O
Linux System Programming - Advanced File I/O
 
Linux System Programming - File I/O
Linux System Programming - File I/O Linux System Programming - File I/O
Linux System Programming - File I/O
 
LCU14 302- How to port OP-TEE to another platform
LCU14 302- How to port OP-TEE to another platformLCU14 302- How to port OP-TEE to another platform
LCU14 302- How to port OP-TEE to another platform
 
Central Processing Unit User View
Central Processing Unit User ViewCentral Processing Unit User View
Central Processing Unit User View
 
Unix system programming
Unix system programmingUnix system programming
Unix system programming
 

Similar to Operating System

Linux kernel debugging
Linux kernel debuggingLinux kernel debugging
Linux kernel debuggingHao-Ran Liu
 
Auditing the Opensource Kernels
Auditing the Opensource KernelsAuditing the Opensource Kernels
Auditing the Opensource KernelsSilvio Cesare
 
Part 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxTushar B Kute
 
AllBits presentation - Lower Level SW Security
AllBits presentation - Lower Level SW SecurityAllBits presentation - Lower Level SW Security
AllBits presentation - Lower Level SW SecurityAllBits BVBA (freelancer)
 
0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdfKhaledIbrahim10923
 
Lec 47.48 - stream-files
Lec 47.48 - stream-filesLec 47.48 - stream-files
Lec 47.48 - stream-filesPrincess Sam
 
Introduction to Assembly Language Programming
Introduction to Assembly Language ProgrammingIntroduction to Assembly Language Programming
Introduction to Assembly Language ProgrammingRahul P
 
Introduction to System Calls
Introduction to System CallsIntroduction to System Calls
Introduction to System CallsVandana Salve
 
Virtual platform
Virtual platformVirtual platform
Virtual platformsean chen
 
The New Systems Performance
The New Systems PerformanceThe New Systems Performance
The New Systems PerformanceBrendan Gregg
 
ppt aman solanki.pptx
ppt aman solanki.pptxppt aman solanki.pptx
ppt aman solanki.pptxHUNNTERRAJPUT
 
OS Services, System call, Virtual Machine
OS Services, System call, Virtual MachineOS Services, System call, Virtual Machine
OS Services, System call, Virtual MachineDivya S
 
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURESOPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURESpriyasoundar
 
COMPUTER BASIC AND FUNDAMENTAL AND ITS ORGANISATION.pptx
COMPUTER BASIC AND FUNDAMENTAL AND ITS ORGANISATION.pptxCOMPUTER BASIC AND FUNDAMENTAL AND ITS ORGANISATION.pptx
COMPUTER BASIC AND FUNDAMENTAL AND ITS ORGANISATION.pptxPannaBushratul
 
Ch2 operating-system structures
Ch2   operating-system structuresCh2   operating-system structures
Ch2 operating-system structuresWelly Dian Astika
 
Linux Initialization Process (1)
Linux Initialization Process (1)Linux Initialization Process (1)
Linux Initialization Process (1)shimosawa
 

Similar to Operating System (20)

LINUX Device Drivers
LINUX Device DriversLINUX Device Drivers
LINUX Device Drivers
 
Linux kernel debugging
Linux kernel debuggingLinux kernel debugging
Linux kernel debugging
 
Prog i
Prog iProg i
Prog i
 
Auditing the Opensource Kernels
Auditing the Opensource KernelsAuditing the Opensource Kernels
Auditing the Opensource Kernels
 
Part 04 Creating a System Call in Linux
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in Linux
 
AllBits presentation - Lower Level SW Security
AllBits presentation - Lower Level SW SecurityAllBits presentation - Lower Level SW Security
AllBits presentation - Lower Level SW Security
 
0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf
 
Lec 47.48 - stream-files
Lec 47.48 - stream-filesLec 47.48 - stream-files
Lec 47.48 - stream-files
 
Introduction to Assembly Language Programming
Introduction to Assembly Language ProgrammingIntroduction to Assembly Language Programming
Introduction to Assembly Language Programming
 
Introduction to System Calls
Introduction to System CallsIntroduction to System Calls
Introduction to System Calls
 
Virtual platform
Virtual platformVirtual platform
Virtual platform
 
The New Systems Performance
The New Systems PerformanceThe New Systems Performance
The New Systems Performance
 
ppt aman solanki.pptx
ppt aman solanki.pptxppt aman solanki.pptx
ppt aman solanki.pptx
 
OS Services, System call, Virtual Machine
OS Services, System call, Virtual MachineOS Services, System call, Virtual Machine
OS Services, System call, Virtual Machine
 
Os note
Os noteOs note
Os note
 
Os lectures
Os lecturesOs lectures
Os lectures
 
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURESOPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
OPERATING SYSTEM SERVICES, OPERATING SYSTEM STRUCTURES
 
COMPUTER BASIC AND FUNDAMENTAL AND ITS ORGANISATION.pptx
COMPUTER BASIC AND FUNDAMENTAL AND ITS ORGANISATION.pptxCOMPUTER BASIC AND FUNDAMENTAL AND ITS ORGANISATION.pptx
COMPUTER BASIC AND FUNDAMENTAL AND ITS ORGANISATION.pptx
 
Ch2 operating-system structures
Ch2   operating-system structuresCh2   operating-system structures
Ch2 operating-system structures
 
Linux Initialization Process (1)
Linux Initialization Process (1)Linux Initialization Process (1)
Linux Initialization Process (1)
 

More from Tuhin_Das

Workshop Assembler
Workshop AssemblerWorkshop Assembler
Workshop AssemblerTuhin_Das
 
Operating System
Operating SystemOperating System
Operating SystemTuhin_Das
 
Clientserver Presentation
Clientserver PresentationClientserver Presentation
Clientserver PresentationTuhin_Das
 
Presentation
PresentationPresentation
PresentationTuhin_Das
 
Malware Trends Developments
Malware Trends DevelopmentsMalware Trends Developments
Malware Trends DevelopmentsTuhin_Das
 
GPS DOCUMENT
GPS DOCUMENTGPS DOCUMENT
GPS DOCUMENTTuhin_Das
 
Presentation On Gps
Presentation On GpsPresentation On Gps
Presentation On GpsTuhin_Das
 
DOCS ON NETWORK SECURITY
DOCS ON NETWORK SECURITYDOCS ON NETWORK SECURITY
DOCS ON NETWORK SECURITYTuhin_Das
 
Brain Machine Interfacenew
Brain Machine InterfacenewBrain Machine Interfacenew
Brain Machine InterfacenewTuhin_Das
 
Laser & Its Application
Laser & Its ApplicationLaser & Its Application
Laser & Its ApplicationTuhin_Das
 
A NETWORK SECURITY APPROACH USING RSA.
A NETWORK SECURITY APPROACH USING RSA.A NETWORK SECURITY APPROACH USING RSA.
A NETWORK SECURITY APPROACH USING RSA.Tuhin_Das
 

More from Tuhin_Das (14)

Workshop Assembler
Workshop AssemblerWorkshop Assembler
Workshop Assembler
 
Aop2007
Aop2007Aop2007
Aop2007
 
SQL
SQLSQL
SQL
 
Operating System
Operating SystemOperating System
Operating System
 
Clientserver Presentation
Clientserver PresentationClientserver Presentation
Clientserver Presentation
 
Presentation
PresentationPresentation
Presentation
 
Malware Trends Developments
Malware Trends DevelopmentsMalware Trends Developments
Malware Trends Developments
 
Malware
MalwareMalware
Malware
 
GPS DOCUMENT
GPS DOCUMENTGPS DOCUMENT
GPS DOCUMENT
 
Presentation On Gps
Presentation On GpsPresentation On Gps
Presentation On Gps
 
DOCS ON NETWORK SECURITY
DOCS ON NETWORK SECURITYDOCS ON NETWORK SECURITY
DOCS ON NETWORK SECURITY
 
Brain Machine Interfacenew
Brain Machine InterfacenewBrain Machine Interfacenew
Brain Machine Interfacenew
 
Laser & Its Application
Laser & Its ApplicationLaser & Its Application
Laser & Its Application
 
A NETWORK SECURITY APPROACH USING RSA.
A NETWORK SECURITY APPROACH USING RSA.A NETWORK SECURITY APPROACH USING RSA.
A NETWORK SECURITY APPROACH USING RSA.
 

Operating System

  • 1. Copyright ©1997 Computer Science 217: Operating System Page 187 November 2, 1999 Operating Systems • Operating systems manage processes and resources • Processes are executing instances of programs • State vector: registers, program counter, memory mgmt registers, etc. code data SV process 3 code data SV process 1 code data SV process 2 state vector: information necessary to start, stop, and restart the process may be the same or different programs user-level processes operating system, “kernel” bare machine assembly & high-level languages machine language & system calls machine language Copyright ©1997 Computer Science 217: Operating System Page 188 November 2, 1999 Privileged Instructions • Machines have two kinds of instructions 1. “normal” instructions, e.g., add, sub, etc. 2. “privileged” instructions, e.g., initiate I/O switch state vectors or contexts load/save from protected memory etc. • Operating systems hide privileged instructions and provide virtual instructions to access and manipulate virtual resources, e.g., I/O to and from disc files • Virtual instructions are system calls • Operating systems interpret virtual instructions
  • 2. Copyright ©1997 Computer Science 217: Operating System Page 189 November 2, 1999 Processor Modes • Machine level typically has 2 modes, e.g., “user” mode and “kernel” mode • User mode processor executes “normal” instructions in the user’s program upon encountering a “privileged” instruction, processor switches to kernel mode, and the operating system performs a service • Kernel mode processor executes both normal and privileged instructions • User-to-kernel switch saves the information necessary to continue the execution of the user process • Another view Operating system is a process that runs in kernel mode. Copyright ©1997 Computer Science 217: Operating System Page 190 November 2, 1999 Virtual Resources • OS provides a high-level representation of low-level resources • For example, low-level disks are presented as file systems simple to use file system tree-structured, hierarchical directories named files files are sequences of bytes network k disk drives different capacities, speeds access via cylinder, sector, track fixed I/O format and transfer rules authentication error correction and handling UNIX Operating System
  • 3. Copyright ©1997 Computer Science 217: Operating System Page 191 November 2, 1999 System Calls • Virtual instructions are often presented as a set of system calls • Typical implementations (in order of prevalence) single privileged instruction with parameters interpret to other privileged instructions jump to fixed locations • Parameters are passed in a machine-dependent manner in fixed registers in fixed memory locations in an argument block, with the block’s address in a register in-line with the system call on the stack combination of the above • System calls return results in registers, memory, etc., and an error indication Copyright ©1997 Computer Science 217: Operating System Page 192 November 2, 1999 System Calls, cont’d • System call mechanism is tailored to the machine architecture system calls on the SPARC use a trap instruction ta 0 trap always; a trap value of 0 indicates a system call parameters are in registers %g1, %o0 — %o5 and on the stack • System call interface often designed to accommodate high-level languages system calls are accessed by a library of procedures e.g., on UNIX, system calls are packaged as a library of C functions • Typical UNIX system call nread = read(fd, buffer, n); returns the number of bytes read from the file fd, or -1 if an error occurs what about EOF?
  • 4. Copyright ©1997 Computer Science 217: Operating System Page 193 November 2, 1999 Implementing System Calls as Functions • In the caller mov fd,%o0 mov buffer,%o1 mov n,%o2 call _read; nop mov %o0,nread • Implementation of read _read: set 3,%g1 /* 3 indicates READ system call */ ta 0 bcc L1; nop set _errno,%g1 /* sets errno to the error code */ st %o0,[%g1] set -1,%o0 /* return -1 to indicate an error */ L1: retl; nop operating system sets the C bit if an error occurred stores an error code in %o0; see /usr/include/sys/errno.h note that read is a leaf function • UNIX has ~150 system calls see “man 2 intro” and /usr/include/syscall.h Copyright ©1997 Computer Science 217: Operating System Page 194 November 2, 1999 Exceptions and Interrupts • Operating systems also field exceptions and interrupts • Exceptions (a.k.a. traps): caused by execution of an instruction e.g., divide by 0, illegal address, memory protection violation, illegal opcode • Exceptions are like implicit system calls operating systems can pass control to user processes to handle exceptions (e.g., “signals”) operating systems have ways to process exceptions by defaults e.g., segmentation fault and core dump • Interrupts: caused by “external” activity unrelated to the user process e.g., I/O completion, clock tick, etc. • Interrupts are like transparent system calls normally user processes cannot detect interrupts, nor need to deal with them
  • 5. Copyright ©1997 Computer Science 217: Operating System Page 195 November 2, 1999 SPARC Traps • A trap instruction enters kernel mode disables other traps decrements CWP saves PC, nPC in %r17, %r18 sets PC to TBR, nPC to TBR + 4 • Hardware trap codes 1 reset 2 access exception 3 illegal instruction ... • Software trap codes sets TBR to trap number + 128 • There are conditional traps just like conditional branches • There are separate floating point traps Copyright ©1997 Computer Science 217: Operating System Page 196 November 2, 1999 System Calls for Input/Output • Associating/disassociating files with file descriptors int open(char *filename, int flags, int mode) int close(int fd) • Reading/writing from file descriptors int read(int fd, char *buf, int nbytes) int write(int fd, char *buf, int nbytes) • Another version of cp source destination (see src/cp1.c) #include <sys/file.h> main(int argc, char *argv[]) { int count, src, dst; char buf[4096]; if (argc != 3) error("usage: %s source destinationn", argv[0]); if ((src = open(argv[1], O_RDONLY, 0)) < 0) error("%s: can’t read ‘%s’n", argv[0], argv[1]); if ((dst = open(argv[2], O_WRONLY|O_CREAT, 0666)) < 0) error("%s: can’t write ‘%s’n", argv[0], argv[2]); while ((count = read(src, buf, sizeof buf)) > 0) write(dst, buf, count); return EXIT_SUCCESS; }
  • 6. Copyright ©1997 Computer Science 217: Operating System Page 197 November 2, 1999 Write with Confidence • Most programs don’t check for write errors or writes that are too large int ironclad_write(int fd, char *buf, int nbytes) { char *p, *q; int n; p = buf; q = buf + nbytes; while (p < q) if ((n = write(fd, p, q - p)) > 0) p += n; else perror("iconclad_write:"); return nbytes; } • perror issues a diagnostic for the error code in errno iconclad_write: file system full Copyright ©1997 Computer Science 217: Operating System Page 198 November 2, 1999 Buffered I/O • Single-character I/O is usually too slow int getchar(void) { char c; if (read(0, &c, 1) == 1) return c; return EOF; } • Solution: read chunks of input into a buffer, dole out chars one at a time int getchar(void) { static char buf[1024]; static char *p; static int n = 0; if (n--) return *p++; if ((n = read(0, p = buf, sizeof buf)) > 0) return getchar(); n = 0; return EOF; } • Where’s the bug?
  • 7. Copyright ©1997 Computer Science 217: Operating System Page 199 November 2, 1999 Implementing the Standard I/O Library • Single-character I/O functions are usually implemented as macros #define getc(p) (--(p)->_cnt >= 0 ? (int)(*(unsigned char *)(p)->_ptr++) : _filbuf(p)) #define getchar() (getc(stdin)) • A FILE holds per-file buffer information typedef struct _iobuf { int _cnt; /* number of characters/slots left in the buffer */ char *_ptr; /* pointer to the next character in the buffer */ char *_base; /* the beginning of the buffer */ int _bufsiz; /* size of the buffer */ short _flag; /* open mode flags, etc. */ char _file; /* associated file descriptor */ } FILE; extern FILE *stdin, *stdout, *stderr; • See /usr/princeton/include/ansi/stdio.h Copyright ©1997 Computer Science 217: Operating System Page 200 November 2, 1999 Buffered Writes • Single-character writes are usually implemented by macros #define putc(c,p) (--(p)->_cnt >= 0 ? (p)->_ptr++ = (c) : _flsbuf((c), (p))) #define putchar(c) (putc((c),stdout)) • Buffering can interfere with interactive streams for (p = "Enter your name:n"; *p; p++) putchar(*p); for (p = buf; ; p++) if ((*p = getchar()) == 'n') break; for (p = "Enter your age:n"; *p; p++) putchar(*p); for (p = buf; ; p++) if ((*p = getchar()) == 'n') break; bug: program waits for input before prompt appears
  • 8. Copyright ©1997 Computer Science 217: Operating System Page 201 November 2, 1999 Buffered Writes, cont’d • Output stream must be flushed before reading the input void fflush(FILE *stream) for (p = "Enter your name:n"; *p; p++) putchar(*p); fflush(stdout); for (p = buf; ; p++) if ((*p = getchar()) == 'n') break; for (p = "Enter your age:n"; *p; p++) putchar(*p); fflush(stdout); for (p = buf; ; p++) if ((*p = getchar()) == 'n') break; • Standard I/O supports line-buffered files #define putc(x, p) (--(p)->_cnt >= 0 ? (int)(*(unsigned char *)(p)->_ptr++ = (x)) : (((p)->_flag&_IOLBF) && -(p)->_cnt < (p)->_bufsiz ? ((*(p)->_ptr = (x)) != 'n' ? (int)(*(unsigned char *)(p)->_ptr++) : _flsbuf(*(unsigned char *)(p)->_ptr, p)) : _flsbuf((unsigned char)(x), p))) • Why is line buffering necessary? f = fopen("/dev/tty", "w")