Professional Documents
Culture Documents
Anupam Basu
Software Engineering Problem: what programmers want/need Optimize for convenience, utilization, security, reliability, etc For Any OS area (e.g. file systems, virtual memory, networking, scheduling): Whats the hardware interface? (physical reality) Whats the application interface? (nicer abstraction)
Translation Map 1
Translation Map 2
The machine designed by Drs. Eckert and Mauchly was a monstrosity. When it was finished, the ENIAC filled an entire room, weighed thirty tons, and consumed two hundred kilowatts of power. http://ei.cs.vt.edu/~history/ENIAC.Richey.HTML
The 6180 at MIT IPC, skin doors open, circa 1976: We usually ran the machine with doors open so the operators could see the AQ register display, which gave you an idea of the machine load, and for convenient access to the EXECUTE button, which the operator would push to enter BOS if the machine crashed. http://www.multicians.org/multics-stories.html
source: New York Times, 2/23/98, page C3, Makers of disk drives crowd even more data into even smaller spaces
Users
16 10s $25,000
32 e1 $4,000
Log of Performance
Microprocessors
Year
1970
1975
1980
1985
1990
1995
Process Management Main-Memory Management I/O System management File Management Networking User Interfaces
System Calls System calls provide the interface between a running program and the operating system.
Generally available as assembly-language instructions. Languages defined to replace assembly language for systems programming allow system calls to be made directly (e.g., C, C++)
System Calls are Used Frequently A single program may make numerous system calls. For example, a program to read from one file and write to another would need system calls for the following:
Prompt the user to enter file names Read in filenames Open input file Read from input file Open/create output file Write output to file Close input and output files
The system must be able to signal and handle errors that occur.
Passing Parameters
Three general methods are used to pass parameters between a running program and the operating system.
Pass parameters in registers. Store the parameters in a table in memory, and the table address is passed as a parameter in a register. Push (store) the parameters onto the stack by the program, and pop off the stack by operating system.
Process Control
A process executing one program may want to load and execute another program (e.g. the shell loads and executes programs). The following are important considerations: Where does control return when the new process is finished?
If return control to existing program, must save memory image of existing program before loading new process. If both programs are to run concurrently, the new process is added to the multiprogramming set of processes.
MS-DOS Execution
MS-DOS runs the command interpreter on startup. It loads a new program into memory, writing over part of the interpreter. When the program terminates, the part of the interpreter not overwritten begins execution. It loads the rest of the interpreter from disk.
At System Start-up
Running a Program
Message Passing Processes use message passing to send messages to one another. First, the connection must be opened. The name of the communicator must be known (hos tname or host id, process name or process id). Use get process id or get host id. open connection, close connection recipient uses accept connection The initiator is the client. The recipient of the request is the server. Exchange of information made with write message system calls.
Shared Memory In memory sharing, processes communicate by writing and reading to the same memory addresses. Processes use map memory system calls to access memory owned by other processes. Both processes must agree to remove O.S. memory restriction so that they can access the same region of memory. The processes are responsible for the form and location of the data. The processes are responsible for making sure that they are not writing to the same memory area simultaneously.
Communication Models
Communication may take place using either message passing or shared memory.
Msg Passing
Shared Memory
System Programs
System programs provide a convenient environment for program development and execution. The can be divided into: File manipulation Status information File modification Programming language support Program loading and execution Communications Application programs Most users view of the operation system is defined by system programs, not the actual system calls.
Simple Structure
MS-DOS written to provide the most functionality in the least space Not divided into modules Interfaces and levels of functionality not well separated
UNIX limited by hardware functionality Original UNIX operating system consists of two separable parts: Systems programs The kernel Consists of everything below the system-call interface and above the physical hardware Provides the file system, CPU scheduling, memory management, and other operating-system functions; Many interacting functions for one level
User Mode
Kernel Mode
Hardware
Modules-based Structure
Most modern operating systems implement modules Uses object-oriented approach Each core component is separate Each talks to the others over known interfaces Each is loadable as needed within the kernel Overall, similar to layers but with more flexible
Interrupts
CPU
Memory
Video Controller
Keyboard Controller
Hardware Components
Processors Memory I/O Devices Buses
I/O Devices
OS must manage I/O devices. User programs can not access I/O devices directly. An I/O device usually consists of two parts: A device controller A chip or set of chips that controls the device. Usually has a microcontroller in it that runs independent of CPU and that is programmed to control the device. The device itself. Examples: A graphics card and a monitor. A hard disk controller and hard disk (drive) itself. A floppy disk controller and a floppy disk drive itself. A printer controller and printer itself. A keyboard controller and keyboard itself. .. A device controller is also called a card or an adapter. Some controllers may not have an associated mechanical device (a network card for example).
I/O Devices
Device
Hardware
Software
I/O types
Polling (busy waiting) Driver polls the controller until data is available or operation is complete Waste of CPU with useless polling (busy waiting) Interrupt driven Driver starts I/O by giving commands to the controller Process is blocked CPU is given to an other process Controller does the job independent of CPU and when finished, gives an interrupt to the CPU. Interrupt service routine of driver takes the data from controller and copies it to the memort The process that was blocked can now continue to run
CPU
4-sends device no
Interrupt controller
User program
Interrupt Vector
OS kernel
Device driver An other device driver
Process Hierarchy
In Unix, processes created by other processes form a hierarchy (with parent child relationships) In Windows, there is no specific hierarchy.
myprogram.o
assembler
data
object file
data data data libraries and other objects
linker
compiler
myprogram.s
data
program
CPU
0 x
common runtime
your program
code library your data address space (virtual or physical)
R0
Rn PC SP x y y high
heap
registers
stack
memory
Process States
As a process executes, it changes state new: The process is being created running: Instructions are being executed waiting: The process is waiting for some event to occur ready: The process is waiting to be assigned to a process terminated: The process has finished execution
Information associated with each process Process state Program counter CPU registers CPU scheduling information Memory-management information Accounting information I/O status information
Context-switch time is overhead; the system does no useful work while switching Time dependent on hardware support
Schedulers
Long-term scheduler (or job scheduler) selects which processes should be brought into the ready queue invoked infrequently (seconds, minutes) (may be slow) Short-term scheduler (or CPU scheduler) selects which process should be executed next and allocates CPU invoked frequently (milliseconds) (must be fast) (Medium-term scheduler)
Process Creation
Parent process create children processes (tree of processes) Resource sharing Parent and children share all resources Children share subset of parents resources Parent and child share no resources Execution Parent and children execute concurrently Parent waits until children terminate Address space Child duplicate of parent Child has a program loaded into it UNIX examples fork system call creates new process exec system call used after a fork to replace the process memory space with a new program
The fork syscall returns twice: it returns a zero to the child and the child process ID (pid) to the parent. Parent uses wait to sleep until the child exits; wait returns child pid and status. Wait variants allow wait on a specific child, or notification of stops and other signals.
fork parent
fork child
int pid = fork(); Create a new process that is a clone of its parent. exec*(program [, argvp, envp]); Overlay the calling process virtual memory with a new program, and transfer control to it. exit(status); Exit with status, destroying the process.
exec
wait
exit
int pid = wait*(&status); Wait for exit (or other status change) of a child.
fork is a simple primitive that allows process creation without troubling with what program to run, args, etc. Serves some of the same purposes as threads. fork gives the parent program an opportunity to initialize the child processespecially the open file descriptors. Unix syscalls for file descriptors operate on the current process. Parent program running in child process context may open/close I/O and IPC objects, and bind them to stdin, stdout, and stderr. Also may modify environment variables, arguments, etc. Using the common fork/exec sequence, the parent (e.g., a command interpreter or shell) can transparently cause children to read/write from files, terminal windows, network connections, pipes, etc.
The Shell
The Unix command interpreters run as ordinary user processes with no special privilege. This was novel at the time Unix was created: other systems viewed the command interpreter as a trusted part of the OS. Users may select from a range of interpreter programs available, or even write their own (to add to the confusion). csh, sh, ksh, tcsh, bash: choose your flavor Shells use fork/exec/exit/wait to execute commands composed of program filenames, args, and I/O redirection symbols. Shells are general enough to run files of commands (scripts) for more complex tasks, e.g., by redirecting shells stdin. Shells behavior is guided by environment variables.
Process Termination
Process executes last statement and asks the operating system to delete it (exit) Output data from child to parent (via wait) Process resources are deallocated by operating system Parent may terminate execution of children processes (abort) Child has exceeded allocated resources Task assigned to child is no longer required If parent is exiting Some operating system do not allow child to continue if its parent terminates: cascading termination (all children terminated)
Can do this by use of execl system call execl replaces the memory image of a process with some new program.
This code creates a child process that will run concurrently with the parent process. Both child process and parent process will execute the same code after the fork() call. The parents memory will be copied to child process, and it will not be shared. Child and parent process can decide which program fragment to run as shown in the following slide
#include <stdio.h> int i, j, char a[1024]; int fd; main(int argc, char *argv[]) { int pid; fd = fopen(myfile.txt, R_ODLY); pid = fork(); /* create a new process */ if (pid < 0) { /* system call is not successful */ fprintf(stderr, fork() failed\n); exit(-1); /* termination with some error */ } else if (pid == 0) { /* this is the child process */ execlp (/bin/ls, ls, NULL); } else { /* this is the parent process */ wait(NULL); /* wait for the child to terminate */ printf(child completed\n); exit(0); /* normal termination */ } }
Process creation
Next slide shows how memory of the parent process is copied to the child process.
pid = 3210
data
data
Parent
Parent
text
Child
Parent id = 2345
Syntax
BOOL CreateProcess( LPCTSTR lpApplicationName, // pointer to name of executable module LPTSTR lpCommandLine, // pointer to command line string LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, // handle inheritance flag DWORD dwCreationFlags, // creation flags LPVOID lpEnvironment, // pointer to new environment block LPCTSTR lpCurrentDirectory, // pointer to current directory name LPSTARTUPINFO lpStartupInfo, // pointer to STARTUPINFO LPPROCESS_INFORMATION lpProcessInformation // pointer to PROCESS_INFORMATION );
STARTUPINFO si; PROCESS_INFORMATION pi; memset(&pi, 0, sizeof(pi)); memset(&si, 0, sizeof(si)); si.cb = sizeof(si); int res = CreateProcess(0, "c:\\windows\\notepad.exe", 0, 0, 0, 0, 0, 0, &si, &pi);
The above code fragment defines two structures related to process creation of type STARTUPINFO and PROCESS_INFORMATION. They will be used by the CreateProcess call to initialize some parameters of the new process. The memset call initialises the newly defined structures si, and pi to 0. Second parameter of CreateProcess is the complete path of the executable. Dont worry about the 0 (NULL) parameters.
void main( VOID ) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); // Start the child process.
if( !CreateProcess( NULL, // No module name (use command line). "MyChildProcess", // Command line. NULL, // Process handle not inheritable. NULL, // Thread handle not inheritable. FALSE, // Set handle inheritance to FALSE. 0, // No creation flags. NULL, // Use parent's environment block. NULL, // Use parent's starting directory. &si, // Pointer to STARTUPINFO structure. &pi // Pointer to PROCESS_INFORMATION structure. ) { ErrorExit( "CreateProcess failed." ); } // Wait until child process exits. WaitForSingleObject( pi.hProcess, INFINITE ); // Close process and thread handles. CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); }
CreateProcess
Terminating Processes