2. OS NOTES 682.23 new LAST 2024[1]

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 85

1

t
050616 "Information technologies" speciality

Lecture Notes
Operating systems subject

V.H. Salimov

[email protected]
http://vagif4.tripod.com

Сopyrigth©2025…V.H.Salimov.All rigths reserved


2

1. Introduction to OS
"The operating systems" subject plays an important role for students are
studying on the speciality "Computer Engineering" . The deep knowledge in this
area allows user work on the computer more freely and programmers design
programs for effectively .

User

OS HARDWARE

Programmers

Various sources give the different definition OS: operating system is computer
manager, operating system is virtual machine, operating system is mediator
among user and computer and others.
According to Wikipedia, the operating system -is a collection of programs that
provide management of technical devices.
All operating systems provide following functions :
1.Support for computer hardware (driver system)
2. User interface
3. File management system
4.Increase effectiveness of usage computer resources (CPU time, RAM,
external memory, external devices) .

Computer include many resources like CPU time, RAM, external memory and
devices. We can consider OS as resources management system
3

In recent years, in functions of OS were included network support and security


services. Additionally many OS include some programming tools such as bat
files and scripting languages (Vbscript and Javascript).
In parallel with the development of computers OS also is changed . On last years
in OS appears new user interface ( intellectual, graphics (GUI), voice. touch
screen) and new technologies increasing productivity and effectiveness of OS
( multitasking, multithreading, multiprocessing, multicore, virtual memory and
others. Development new type of mobile computers (smart phones, tablets) witch
change the OS. Mobile OS include large communication features (phone,
Internet). Android is based on LINUX principles and was written on C++

2. Architecture of processor

To understand the principles of the operating system is required knowledge


about the devices and particularly processor and processor interrupt system. A
simplified diagram of the X86 processor personal computer is shown in Fig.

Control
Unit
Arithmetic
I / O Devices
Logic Unit
Main
Registers Disk Printer
Memory

Bus
4

CPU central processing unit

The processor has a complex construction. The main component


are - ALU (Arithmetic logical unit), the control unit and registers .
Register is a small ultra-fast memory . The registers are mainly 8, 16, 32 and 64
bits.
The registers are used for temporary storage of various information:
instructions, data..
Prosessors İntel Intel X86 include several registers

1. General purpose registers AX, BX, CX, DX


AX (Accumulator) - used when performing arithmetic operations and
I / O operations
BX (Base Registr) - used as index registr adresses
CX (Count registr) - used for looping
DX (Data registr) - I / O operations

2. Segment registers

CS (code seqment) stores the start address of the program code


DS - (data seqment) stores the start address of the data segment
SS - (Stack seqment) also stack
ES (extra seqment) also for dopolnitel'nog segment

3. Counter instruction address


İP (İnstruction Point) - indicates the address of the current instruction
FR -flag registr
5

Major flags

Original processor X86 is 16 bits one. Today most used more advanced 32 and 64
bits multicore processors.
They also have same registers but twice large ( except segment registers they keep
16 bits) 32 bits registers have prefix E so not AX EAX not BX EBX.
64 bits registers have prefix R so not AX RAX and so on.
IP — 16bits
EIP — 32 bits
RIP — 64 bits
Segment register have same size for all models 16 bits
Data registers in 32 CPU. 32 bits
EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI,
Data register in 64 CPU. 64 bits

RAX, RCX, RDX, RBX, RSP, RBP, RSI, RDI


6

64 RAX RBX RCX RDX


32 EAX EBX ECX EDX
16 AX BX CX DX
AH AL BH BL CH CL DH DL

64 RSP RBP RSI RDI


32 ESP EBP ESI EDI
16 SP BP SI DI
SPL BPL SIL DIL

3. Interrupt system
As has been shown above as well as under unforced management processor
time, there is a need in the temporary program switch that requires preservation of
all program options and first registers. All the information on the process required
to restore it again referred to the context. The context of the process is stored in a
special structure called a process control block. PCB(Process Control
Block). Together with the handle to form a complete description of the

process . The most important part of your computer is the


interrupt controller. Interrupt controller is a special electronic unit is placed on the
motherboard. The purpose of this system of identification of various emergency
situations which is happened in computer organization and mechanism of the
reaction to these events. The computer account several interruptions, each
assigned a specific code and software-defined interrupt handler. All interrupts are
divided into internal and external:
External interrupts:
- Interrupts from external devices;
7

- Timer interrupt;
- user interrupt
Internal interrupts
- Incorrect addressing
- Division by zero
- The output value of a variable outside
- programmed interruptions
OS work closely related system interruptions and first timer interrupt. On the basis
of the timer interrupt process is implemented switching mechanism.

4. Descriptor and Context of processes

Any process and thread has 2 group characterictics –descriptor and context
.Descriptor include general information about process .

As standard descriptor include following information :

1. Prosses identificator;

2. Relation to other process ( main or sub)

3. Information to define priorities

4. Prosses state

5. Prosses creating time and required time

6. Required memory

7. Required I/O devices

8. Owner of process

Context include information required for restoring process after unterrupting


Basically any time in computer are presented 100-1000 processes and all of them
must managed by OS.
If OS used threads then for any thread organized context
Any process may be in different states
- running state ( prosses in CPU)
8

- ready ( in ready queue )


-waiting
-completed

To manage processes OS needs to some actulal information and it is called


context

1. Process state

2. Address of last instruction

3. State of all registers

4. priorities

All these information are stored in special memory space PCB (proses control
block )

PCB

Deskriptor Context
9

5. PROCESSES and THREADS


Process and thread are main terms of OS. Process in OS is synonym of
program or application. A thread is a path of execution within a process,
basically subprogram. Process can contain multiple threads. The typical
difference is that threads within the same process run in a shared memory space,
while processes run in separate memory spaces.

Threads basically is designed for multicore processors, any thread is loaded in


corresponding core. But can use in single core processors.
As known thread its some part of program which can run independatly of others .
Modern OS support multitasking mode which organize concurrently
implementation of processes and threads. Concurrently it is situation when some
process or thread get some kvant of CPU time, and periodically switch to other
process or thread. A concurrency efficiently on a single core processor .
Multicore processors allow to organize not only concurrency and papalleliыm
Very important !!!
Don’t confuse concurrency and parallelism!!!!
10

In single core computer parallel processing


impossible !!!
In single core PC concurrent processing can be presented like

In multicore computers (today most of PC) possible concurrent


and parallel processing
11

Hyper-threading (mix parallel and concurrency)

Difference between Process and Thread


S.N
Process Thread
.

1 Process is heavy weight or Thread is light weight, taking lesser


resource intensive. resources than a process.
12

2 Process switching needs Thread switching does not need to interact


interaction with operating with operating system.
system.

3 In multiple processing All threads can share same set of open


environments, each process files, child processes.
executes the same code but
has its own memory and file
resources.

4 If one process is blocked, then While one thread is blocked and waiting, a
no other process can execute second thread in the same task can run.
until the first process is
unblocked.

5 Multiple processes without Multiple threaded processes use fewer


using threads use more resources.
resources.

6 In multiple processes each One thread can read, write or change


process operates another thread's data.
independently of the others.

Advantages of Thread
 Threads minimize the context switching time.

 Use of threads provides concurrency within a process.

 Efficient communication.

 It is more economical to create and context switch threads.

 Threads allow utilization of multiprocessor architectures to a greater scale and


efficiency.

6. OS history

History of OS development is closely related with the changes of computers.


Usually it is also divided into 4 periods.
The first period covers 1946-1956 years. During this period (the first generation of
computers operating system actually consisted of a programming language
13

compiler (at the time it is Assembler and Fortran) and the loader program. Initially
loaded and then performed compiler program and performance load.

Programs were entered from the panel or from a perfocards. When an error is
detected the perfo card preparing again and the process repeated.

The second period covers 1956-1966 years. During this period, there was the
first real OS and the first -Batch processing system
With this technology, the end user does not have direct contact with the
operating system, all applications is processed by the operator (specialist having
authorized access to the computer). Each packet is processed automatically, the
program selected from the packet and run. After processing the results are
delivered to the user. If error are happened process is repeated. The basic idea of
14

this technology –increase system capacity, due to the exclusion from the process
end user to work directly on the computer and achieve some savings time.
To further improve system performance by increasing the load by processor
was designed multiprogramming technology(multiprogramming). The basic idea
of this technology the fact that if in the performance of any program needs to
input / output and is released , the processor in this period can be used to load
another programs. After the completion of the I / O operation is interrupted, the
program returns to the queue of ready programs. This provides an increase CPU
utilization. This technology is called non preemptive , i.e. the second process
starts if this allows the first process.
15

Batch processing multiprogramming is used in DOS IBM 360.


16

The third period is 1965-1975 years, during this period there were first terminals
(monitor and keyboard) and there was an interactive mode of operation, of course
the user for the first time to get direct access to computer.
During this period, a new technology is the use of time-sharing computers -
mode (time sharing), providing a pseudo simultaneous access to your computer
many users (multiusering). The essence of the time-sharing mode is that each user
is given a certain small CPU (quantum or slice ).Quantum size is chosen so that the
user has created a sense of exclusive possession of all the
computer (virtual machines) . After completion of the quantum control is passed
to another user. The main purpose of operating time-sharing to ensure the
maximum comfort for users.
The fourth period began in 1975 and continues to the present. This
is due primarily to the advent of the personal computer (1981) and the
first multitasking system Ms Windows 3.1. At the heart of multi-tasking
technology, is at the same time (pseudo simultaneously, i.e the apparent
simultaneous) execution of several programs. Here, as well as time-
sharing but each program is given a small CPU time (slice) and a user
creates the illusion that all programs are working in parallel such as (Ms Word,
Media Player, Internet Explorer, MS Outlook, Kaspersky AntiVirus). If
multiprogramming mode is aimed at improving the efficient use of the processor,
the multitasking mode is aimed at creating a useful illusion running in parallel
operation of several programs .

In the operating systems Ms Windows and more new multi-threading


mode (multithreading) appeared along with a multitasking mode. There is
provided psevdo paralell mode between the routines of one such program (in Ms
Word and print text and mode Autosave). With the advent of multi-core
processors to the operating system goes to new load is the effective capacity
17

planning .The structure of modern operating systems tasks also include security
issues and support networks.

7. Classification of OS
The are many classifiction of OS : by number of users OS may be single user
and multi user. By number of parallel running programs OS is diveded into multi
programming and single programming. In multiprogramming OS may be used 2
technologies non preemtive (multiprogramming) and (preemtive))
(multitasking) . By number of processors OS may be one processor and multi
processing. By number of cores one and multicore. And according to use threads :
one thred and multithreding.

By proccesing technology OS is divided into 3 categories.:

1. Batch proccesing systems .Here user not active participate in execution


process. Any user present own task (program) and its characteristics
( required time, memory, i/o devices). On base on this information OS
planning work to achive MAX CPU utilization. These systems basically
are used in mainframe computers.
2. Interactive systems. Most used system basecally in personal computers
(MS Windows, Unix, Linux).Here are used multitasking and multithreading
technologies. Often support multiusering.
3. REAL time systems .
These systems are used in control systems ( car, airplan, production process) .
In these systems are predifined list of programs and their duration and deadline
time. Main requirements all programs must executed and any program must
executed not later than deadline time.
Modern OS classification
18
19
20

8. Architecture of OS

Os is very complex program. By function classification OS include


following modules:

-main module
- CPU time manager
- RAM memory manager
- disk memory manager
-user manager
OS has ierachical architecture main module kernel and functional modules..
21

The kernel (also called nucleus) is a computer program that constitutes the
central core of a computer's operating system. It has complete control over
everything that occurs in the system. As such, it is the first program loaded on
startup, and then manages the remainder of the startup, as well
as input/output requests from software, translating them into data
processing instructions for the central processing unit. It is also responsible for
managing memory, and for managing and communicating with
computing peripherals, like printers, speakers, etc. The kernel is a fundamental part
of a modern computer's operating system.

A kernel connects the application software to the hardware of a computer

The critical code of the kernel is usually loaded into a protected area of memory,
which prevents it from being overwritten by other, less frequently used parts of the
operating system or by applications. The kernel performs its tasks, such as
executing processes and handling interrupts, in kernel space, whereas everything a
user normally does, such as writing text in a text editor or running programs in a
GUI (graphical user interface), is done in user space. This separation prevents user
data and kernel data from interfering with each other and thereby diminishing
performance or causing the system to become unstable (and possibly crashing).

When a process makes requests of the kernel, the request is called a system call.
Various kernel designs differ in how they manage system calls and resources.

Additional modules are transit programs :

-utilities

- editors Additional modules

Kernel

hardware
22

Kernel has different architecture :

-monolit, module, Mikro, Nano,ekzo, qibrid. Most simple monolit , others is


designed to increase flexability.

9. Structure of processes in OS

Any program( process or thread) to be executed on the computer must has


CPU time, Ram memory, I/O devices. The main function of OS is manage these
resources and shared them between all processes (threads).
For manage resources OS needs to some information. First processes is
divided into type short <100 mks, long>100 mks. Second it is structure of
processes relation between cpu processing and I/O processing
CPU birst – time when process in CPU
I/O birst-time when process in I/O
23

Fig. Structure of process

CPU planning depend of OS type packet, interactive and real time

For packet systems are used following criterias

a) MAX CPU utilization


b) Max throunghput number of tasks complited by one time unit (1 minute, 1
hour)
c) Min turnaround average time spent for one program

If in system are presented n processes and I/O birst = P (%) then


CPU utilization =1-Pn formula is true

CPU utilization as function of number of processes

In batch OS are used 3 algorithms

10. FCFS algorithm


24

1. FCFS (First come First served). First process is loaded to CPU and
start execution up to first I/O operation. When this process meets with
I/O it removed to waiting state and second process is loaded to CPU.
When I/O operation is finished first process return in front of ready
queue and second process is removed into waiting queue.

Example

1. First Come-First Served


The 3 processes are admitted in .
Process A 3 seconds. completed.
Process B 2 sec. completed
Process C 1 sec. complited
In FCFS processes are carried out in the following sequence:
A-B-C
Processes Required time Completion Waiting time
time
A 3sec 3 sec 0
B 2 sec 5 sec 3
C 1 sec 6 secs 5
The average completion time is calculated by the following formula:
(P 1 + P 2 + P 3 ... P n) / n
(3 + 5 + 6) / 3 = (14/3), or 4.67 sec
The average waiting time
(Q 1 + Q 2 + Q 3 ... Q n) / n
(0 + 3 + 5) /3=2.66 sec
25

FCFS disadvantage is not diffrences between short and long processes and in
this case short processes may be very long time waits long processes
(supermarket)

11. SJF preemtive algorithm

Short processes problem is solved in SJF (shortest job first) algorithm .Here is
used technology when shortest process get max priority and is loaded in cpu first

EXAMPLE
2. Shortest Job First (Non preemptive)
Process A 3 seconds. completed.
Process B 2 sec. completed
Process C 1 sec. completed.
In the following sequence of processes are executed SJF:
C-B-A
Processes Required time Completion Waiting time
time
A 3 sec 6 3 sec
B 2 sec 3 1 sec
C 1 sec 1 0 sec
The average completion time is calculated by the following formula:
(P 1 + P 2 + P 3 ... P n) / n
(6 + 3 + 1) / 3 = (10/3), or 3.33 sec
The average waiting time
(Q 1 + Q 2 + Q 3 ... Q n) / n
(3 + 1 + 0) / 3 = (4/3), or 1.33 sec

12. Shortest-Remaining-Time (SRT) Scheduling


26

Shortest remaining time (SRT) scheduling is the preemptive version of SJF. In


SJF once a job begin executing, it runs to completion. In SRT a running process
may be preempted by a process with a shorter estimated time.
For example consider the following table
Process Arrival Time Burst Time
P1 0 10
P2 1 6
P3 2 9
P4 3 4
At time t=0, Process P1 will start get executing as it is only the process present at that time. Then
at t=1, Process P2 added to the CPU scheduler, at this time remaining time(Burst time) for
Process P1 gets 9, as Burst time of P2 is less than the remaining time of other processes (for now
there is only process P1) therefore process P1 is preempted and P2 is alloted the CPU.
This process is repeated until all process get executed. This is known as Shortest Remaining
Time Algorithm..
27

13. Determining Length of Next CPU Burst

Shortest Job First (SJF) is an optimal scheduling algorithm as it gives maximum


Throughput and minimum average waiting time(WT) and turn around time (TAT)
but it is not practically implementable because Burst-Time of a process can’t be
predicted in advance.
We may not know the length of the next CPU burst, but we may be able to predict
its value. We expect the next CPU burst will be similar in length to the previous
ones. By computing an approximation of the length of the next CPU burst, we can
pick the process with the shortest predicted CPU burst.
There are two methods by which we can predict the burst time of the process :
1. Static method – We can predict the Burst-Time by two factors
:

 Process size –
Let say we have Process Pold having size 200 KB which is already executed and
its Burst-time is 20 Units of time, now lets say we have a New Process
Pnew having size 201 KB which is yet to be executed.
We take Burst-Time of already executed process Pold which is almost of same size
as that of New process as Burst-Time of New Process Pnew.
 Process type –
We can predict Burst-Time depending on the Type of Process. Operating
System process(like scheduler, dispatcher, segmentation, fragmentation)
are faster than User process( Gaming, application softwares ). Burst-Time
for any New O.S process can be predicted from any old O.S process of
similar type and same for User process.
Note – Static method for burst time prediction is not reliable as it is always not
predicted correctly.
2. Dynamic method – Let ti be the actual Burst-Time of ith process and
Τn+1 be the predicted Burst-time for n+1th process.
 Simple average – Given n processes ( P1, P2… Pn)

Τn+1 = 1/n(Σi=1 to n
ti)
 Exponential average (Aging) –
 Can be done by using the length of previous CPU bursts,
using exponential averaging
28







Prediction of the Length of the Next CPU Burst (α = 0.5)

14. Interactive OS .RR algorithm

a. Min response time


b. Min waiting time
In these systems basically is used RR (Round Robin) algorithm. In this
algorithm any process sequintally get some quantum time (0.2 mks) and
29

return in tail of queue. First problem in this algorithm is size of


quantum. If quantum very short is increased cost of management, if
quantum big then we have some delay.

Max

HASAY
HA
Example
3. Round Robin
Process A 3 seconds. completed.
Process B 2 sec. completed
Process C 1 sec. complited
Each quantum process is set to 500 msec.
In RR algorithm processes carried out in the following sequence
A-B-C-A-B-C-A-B-A-B-A (for 2 quantum)
30

Processes Required time Completion Waiting time


time
A 3 sec 6 sec 3 sec
B 2 sec 5 sec 3 sec
C 1 sec 3 sec 2 sec

The average completion time is calculated by the following formula:


(P 1 + P 2 + P 3 ... P n) / n
(3+ 6 + 5) / 3 = (14/3) = 4.66 seconds
The average time
(Q 1 + Q 2 + Q 3 ... Q n) / n
(3 + 3 + 2) / 3 = (8/3), or 2.66 sec

In reality some processes are more important than others.


In this case priorities mechanizm is used so process with higher priority has more
CPU time. Priority may be static (unchangeable) and dynamic.

4. RR with priorities
Process A 3 seconds. completed. (priority 1)
Process B 2 sec. completed (priority 2)
Process C 1 sec. completed. (priority 2)
Each quantum process is set to 500 msec.
The following sequence of processes executed
A (6 quantum) -B-C-B-C-B (2 quantum)
Processes Required time Completion Waiting time
time
A 3 sec 3 sec 0 sec
B 2 sec 6 sec 4 sec
C 1 sec 5 sec 4 sec
The average completion time
(P 1 + P 2 + P 3 ... P n) / n
(3+ 6 + 5) / 3 = (14/3) = 4.66 sec
The average waiting time
(Q 1 + Q 2 + Q 3 ... Q n) / n
(4 + 4 + 0) / 3 = (8/3), or 2.66 sec

In some systems are used multi queues system, it means is organized multi level
queueies. Firstly are processing tasks from queue 1 , when are completed, system
switchs to Level 2 and so on,
31

15. Multilevel Queue scheduling


2 terms:
Starvation – low priority processes may never execute
Aging – as time progresses increase the priority of the
process

Many variant exist.


Ready queue is partitioned into separate queues, eg:
 foreground (interactive)
 background (batch)
Process permanently in a given queue
Each queue has its own scheduling algorithm:
foreground – RR
background – FCFS

Scheduling must be done between the queues:


Fixed priority scheduling; (i.e., serve all from foreground then
from background). Possibility of starvation.
Time slice – each queue gets a certain amount of CPU time
which it can schedule amongst its processes; i.e., 80% to
foreground in RR
20% to background in FCFS
32

Multilevel Feedback Queue


 A process can move between the various queues; aging can be
implemented this way
 Multilevel-feedback-queue scheduler defined by the following
parameters:
 number of queues
 scheduling algorithms for each queue
 method used to determine when to upgrade a process
 method used to determine when to demote a process
 method used to determine which queue a process will enter
when that process needs service

Example of Multilevel Feedback Queue


 Three queues:
 Q0 – RR with time quantum 8 milliseconds
 Q1 – RR time quantum 16 milliseconds
 Q2 – FCFS
Scheduling
 A new job enters queue Q0 which is served FCFS
 When it gains CPU, job receives 8 milliseconds
 If it does not finish in 8 milliseconds, job is moved to
queue Q1
 At Q1 job is again served FCFS and
receives 16 additional milliseconds
 If it still does not complete, it is
preempted and moved to queue Q2
33

16. Real time OS


İn this systems for any process completion is defined some limits and
OS try to satisfied it.
These system is divided to 2 group
 With hard requirements –plant processes
 With soft requirements it means that little violation is allowed – audio and
video systems
Events which are related with real time systems can be divided in two group:
 periodic – audio and video
 non periodic – fire signals and other
For planning periodic real time systems we must satisfied folowing main
condition:

m – quanataty of periodic processes ı


i – process’s index
P(i) – period
T(i) – required time
If this condition is not satisfied it means inpossible planning
Example 3 prosses are given ( video stream)
Process А must start any 30мs r, processing time ı 10мs
Process В must start any 40мs, processing time ı 15мs
Process С must start any 50 ms, processing time ı 5мs
34

Three periodic processes


Checking condition.
10/30+15/40+5/50=0.808<1
Is satisfied it means planning possible .
There are 2 algorithms of planning static and dynamic
1. Statik RMS (Rate Monotonic Scheduling) algorithm
In this algorithm priorities are defined according to frequencies
Priority of process A 33 (1/30)
Priority of process B 25 (1/40)
Priority of process C 20 (1/50)
Processes are running according to priorities
35

Algorithm RMS (Rate Monotonic Scheduling)

In Figure , initially all three processes are ready to run. The highest priority
one, A, is chosen, and allowed to run until it completes at 15 msec, as shown in
the RMS line. After it finishes, B and C are run in that order. Together, these
processes take 30 msec to run, so when C finishes, it is time for A to run again.
This rotation goes on until the system goes idle at t=70. At t=80, B becomes
ready and runs. However, at t=90, a higher process, A, becomes ready, so it
preempts B and runs until it is finished, at t=100. At that point the system can
choose between finishing B or starting C, so it chooses the highest priority
process, B
An example of EDF is given in Figure 3-2. Initially all three processes are
ready. They are run in the order of their deadlines. A must finish by t=30, B must
finish by t=40, and C must finish by t=50, so A has the earliest deadline and thus
goes first. Up until t=90 the choices are the same as RMS. At t=90, A becomes
ready again, and its deadline is t=120, the same as B's deadline. The scheduler
could legitimately choose either one to run, but since in practice, preempting B
has some nonzero cost associated with it, it is better to let B continue to run

2. Algorithm with dynamic priorioties EDF (Earliest Deadline First)


Highest priority is given to process has minimum remaining time .
36

Example
Process А must start any 30мs r, processing time ı 15мs
Process В must start any 40мs, processing time ı 15мs
Process С must start any 50 ms, processing time ı 5мs
.
Checking condition ., it possible
15/30+15/40+5/50=0.975<1
CPU load 97.5%

With RMS, the priorities of the three processes are still 33, 25 and 20 as only
the period matters, not the run time. This time, B1 does not finish until t=30, at
which time A is ready to roll again. By the time A is finished, at t=45, B is ready
again, so having a higher priority than C, it runs and C misses its deadline. RMS
fails.
EDF algorithm (Earliest Deadline First)

Here RMS has failure .but EDF works

17.Synchronization of processes.
37

The processes in OS usally are interrelated . It is required its synchronization


in otherwise may be some conflicts. For example, imagine we have database, one
process write data into database other at same time try to read them . If we do not
apply special prevent actions we will meet some problems.
38

Other problem when several programs try to get access to same device, for
example printer.
To solve these problem system must use special rule: if some process try to get
access to some resourse , process must recognize this resourse is free or busy. If
resourc e free then process take it and protect to acces from other programs
There are several methods.
Global variables . Programmer for any resourse create special logical
variable ( 0 or 1). This variable is called FLAG . How is seen in
flowchart program enter into critical section the flag is checked . If
resours is free then F(D)=1 and program begin work with resourse and
set to F(D)=0, 0-busy 1- free

This method has one big disadvantage – when some process is running others
without success check value of global variable. To solve this problem was
proposed metod of critical section. According to this method program send to
operating system ( Ms Windows) special mesage EnterCriticalSection(). Here
also used global variable , but but when resours is busy other program switched
39

to waiting queue . When process complets work with this resours send mesage to
Ms Windows LeaveCriticalSection() and processes from waiting queue try to
get access to resoures. .

Next method is named semaphor method. Semafor like global variable but
here are used integer variable , if resource is busy V(S)=KMAX, where KMAX is
number of resourses , if V(S)>0 it means some resourese is free and procees can
use it. When process occupate some resource it add 1 to V(S)+1, when process
disoccupate this resource P(S)-1 is exucuted

18. Deadlock management . Resourses.


Dead lock . For example we have two processes A and B . Process A firstly
needs to printer and next disc , Process B opposite first needs to disc and next
printer. In this case Procees A blocked B and B blocked A .
40

We now want to abstract the concept of deadlock, and apply it to all resources that a
computer system may have. We will see that in some cases the resources can be
shared without any chance of deadlock. However, in other cases it is possible for
several processes to be waiting for resources that they will never be able to allocate.

Resources
For the purposes of our discussion a resource is an object that a process makes use
of. A resource can be a piece of hardware such as
 tape drive
 disk drive
 printer
 etc.
or a piece of information such as
 a file
 a record within a file
 a shared variable
 a critical section
 etc.
A computer typically has many different resources. In some cases there may be
many instances of a resource of a given type (e.g. buffers), all of which are
equivalent. A process needing one of these resources can use any one of them. In
other cases there may be only one instance of a resource (e.g. CD-ROM drive with
a particular CD).
Resources come in two flavors: preemptable and nonpreemptable. A preemptable
resource is one which can be allocated to a given process for a period of time, then
be allocated to another process and then be reallocated to the first process without
any ill effects. Examples of preemptable resources include
 memory
 buffers
41

 CPU
 array processor
 etc.
A nonpreemptable resource cannot be taken from one process and given to
another without side effects. One obvious example is a printer: certainly we would
not want to take the printer away from one process and give it to another in the
middle of a print job. (Actually, the THE operating system treated printers as
preemptable resources -- the operators would have to sort the printed output to
reassemble print jobs.)
As we shall see, deadlocks usually involve nonpreemptable resources. The usual
sequence of events that occur as a resource is used is
1. Request the resource. One of two things can happen when a
resource is requested: the request can be granted immediately
(if the resource is available) or it can be postponed (or blocked)
until a later time.
2. Use the resource. Once the resource has been acquired, it
can be used.
3. Release the resource. When the process no longer needs the
resource it releases it. Usually it is released as soon as possible
but in most systems there is nothing to enforce this policy.

Definition
Tanenbaum and Woodhull define deadlock as:
A set of processes is deadlocked if each process in the set is waiting for an event that only
another process in the set can cause.
42

Notice that it is possible for a single process to become deadlocked if it is waiting


for an event that only it can cause. However, it is usually the case that one process
is waiting for a resource that is held by another process. If the other process is itself
waiting for a resource held by the first then deadlock occurs.
Note that deadlock is different from starvation. Starvation is the problem that
occurs when a process is waiting for a resource that is allocated to other processes,
released, and then allocated again to some process other than the one that is
starving.

19. Deadlock conditions


In 1971 Coffman et al. showed that four conditions must hold in
order for deadlock to occur:
1. Mutual exclusions: Each resource can be assigned to only
one process at a time and is either assigned or available.
2. Hold and wait: Processes that currently hold resources can
request and wait for additional resources.
3. No preemption: Resources previously granted cannot be
taken away from the processes that hold them; they must be
released by the holding process.
4. Circular wait: There must be a circular chain of two or more
processes, each waiting for a resource held by the previous
member of the chain.
All four of these conditions must hold in order for deadlock to occur

20. Methods of deadlock solution


43

There are four different approaches to dealing with the deadlock


problem:
1. Ignore the deadlock problem
2. Deadlock Prevention
3. Deadlock avoidance
4. Deadlock Detection and recovery
Ignore the Deadlock Problem
This is the approach taken by most operating systems. In fact, this is
really an instance of the second approach: deadlock detection and
recovery. This is because a human operator will often notice the
deadlocked condition (detection) and kill the offending process(es)
or restart the system (recovery). The implicit assumption here is
that deadlock is unlikely to occur, and when it does it is relatively
easy (and inexpensive) to recover from.
This is not quite as bad as it sounds. As we will see, handing the
deadlock problem is complicated and is often inconvenient. If it is
the case that a given system is likely to suffer from deadlock
infrequently (once a week, once a month, etc.) but for other reasons
it is restarted at least that frequently (e.g., it is restarted every
morning) then it's probably not worth much effort to worry about
deadlock.
Another consideration is exactly what types of processes are
suffering from deadlock. If user processes are likely to be the only
processes that become deadlocked, and they can be killed and
restarted easily, then deadlock detection, avoidance or prevention is
not mandatory. However, if it is kernel processes that are becoming
deadlocked, so that the system is unusable, then it is probably
worth some effort to eliminate the deadlock problem.

Deadlock Prevention
Deadlock prevention algorithms ensure that at least one of the
necessary conditions (Mutual exclusion, hold and wait, no
preemption and circular wait) does not hold true. However most
prevention algorithms have poor resource utilization, and hence
result in reduced throughputs.

Deadlock avoidance

As you saw already, most prevention algorithms have poor


resource utilization, and hence result in reduced throughputs.
44

Instead, we can try to avoid deadlocks by making use prior


knowledge about the usage of resources by processes including
resources available, resources allocated, future requests and future
releases by processes. Most deadlock avoidance algorithms need
every process to tell in advance the maximum number of resources
of each type that it may need. Based on all these info we may
decide if a process should wait for a resource or not, and thus avoid
chances for circular wait.

A resource allocation graph is generally used to avoid deadlocks.


If there are no cycles in the resource allocation graph, then there
are no deadlocks.
Deadlock Detection and recovery

If deadlock prevention and avoidance are not done properly, as


deadlock may occur and only things left to do is to detect the
recover from the deadlock. Here is used special graph called wait-
for-graph. Analysis of this graph permit indicate deadlook

So the system can maintain a wait-for-graph and check for cycles


periodically to detect any deadlocks. Once a deadlock is detected,
you will have to break the deadlock. It can be done through
different ways, including, aborting one or more processes to break
the circular wait condition causing the deadlock and preempting
resources from one or more processes which are deadlocked.

21. Primary memory management. Overley method.

Types of memory
45

It is clear that to running some process it needs to CPU time and some
RAM space. In multitacking system we meet to problem with memory
planning .
In single program system situation like to presented on the picture.

OS

User program

Free space
46

From picture is clear that if the memory is enough , then no problem ,


othercase we need to manage this problem. Historical first and very
effective method is OVERLEY. To use this method we must split
our program on many subprogram. First is loaded main program
next will be loaded subprogram 1, when we load subprogram2 , it
will be load over subprogram1. This process will be applyed to other
subprogram.
In multiprogramming system for memory management are used 2
methods
1. With usage disk memory
2. Without disk memory
General classification is
47

22. Fixed partition method

1. In this method all memory is divided on fixed number memory


partition and any program is loaded in own partition.
disadvantage
a) May be program more the maximal partition, in this case
process can be executed
b) May be program less then partition, we will lost small
fragments in anay partition.
48

23. Variable partition method

1. In this method we do not in advance split memory to partitions. Program is


loaded dymanic.When the first program is loaded , other spase memory can
be used for second program. Disadvantage fragmentation may be, to manage
this problem system collects free fragments and organize whole partition,
but it needs to additional time.
49
50

24. Virtual memory method


Virtual memory it is one part of system disc which is used as
contunues of real primary memory (RAM). Here are used 3 methods

1. Page method. RAM memory logicaly is divided in to fixed partition ( 512 ,


1024 bytes ). Os try load all program, if memory is not enough, OS temporay
remove some pages of other program to virtual memory. When program is neded
to this page ,OS remove other page. Disadvantage-needs additionaly time for
swapping pages.
51

2. Segment method ,Same as page method but segment does not have fixed
size . Segment size is determined according to submodules of program.
3 Segment-page method It is combination of two previos methods, use segment
method and for any segment is used page method.
ALGORITHMS OF REPLACEMET

FIFO: (First In First Out)


•The oldest page in the physical memory is the one selected for replacement.
•Very simple to implement.
Issues:
•poor replacement policy
•FIFO doesn't consider the page usage.

LRU (Least Recently Used): In this algorithm, the page that has not been used for longest
period of time is selected for replacement.

25. File system. FAT and NTFS


52

It is known that one of the basic functions of the operating system is the creation
and support of file systems. Effective management of the file system is : the most
compact, high-speed access, search, storage security. We know that the file is
located on a computer external memory. Each file has a name, extension, creation
date, security attributes, and more. The file system is built on the principle of
traditional libraries, i.e., there are directories and files.
According to the file allocation method in memory distinguish continuous
and distributed representations. By reading technology files are sequential and
direct access. Information is written to the disk by clusters. Each cluster consists
of an some number of sectors. Each sector has a standard capacity of 512
bytes. In Ms Windows, used mainly two file systems: Fat32 and NTFS.
1. FAT (file allocation table)
The file system is created in the process of formatting a disk. During this process,
a special service information such as boot record, the main directory, Fat table
and its copy are created. Files are stored separately from the directory. That is, the
directories indicate the file location address. There are two versions of FAT FAT16
and FAT32 (since 1997).
Architecture of FAT system
The boot sector. BIOS FAT FAT (copy) Root Area files
parameter block directory
FAT ( file allocation table) like one dimension array, size of this array equal to
number of clusters on the disc. Any element of FAT is 2 bayt ( 16 bits) space in
FAT16, and 4 bayt(32 bits) in FAT32.
For empty cluster on the disc FAT stores 2 zeros (00), End of file is indicate as
FF. Other elements of FAT store address of next cluster of file. FAT16 means that
used 16-bit pointers, that total space 2 16 = 65536 cluster storage and support up to
4GB disks . FAT32 uses 2 32 clusters=4 294 967 296 clusters and can
addressed 2TB disks. Numbers of directories in FAT 16 is
limited=512, FAT32 unlimited.
For each file in the directory created his own record. Structure:
53

8 3 1 10 2 2 2 4
File Extension Attributes Backup Time date Number The size
name copy of first
block

2. NTFS system has some advantages :


1. Unlimited disc space 264 byte = 1
Ekzobayt=16000 GB.=16 TB Largest file size 232 clusters and
size of cluster from 512 bayt up to 64 KB.
2. Rollback system
3. data compressing
4. data encrypting
5. data security by autorization
Disadvantage- some reduce speed

26. Management of external devices in OS

OS management of external devices include 2 basic functions:


1. provide all external devices by drivers
Modern operating system provides a mechanism Plug and Play , to search for and
selection of the appropriate driver
2. cooperative e use of external devices by multiple processes. There are 3
approaches:
- Monopoly - the device until the end of the program are given in the process of
disposal.
- Sharing - device are used simulatesly by several program by time sharing
technology
- Virtual - instead real device is used some virtual device basically disc.
In the first method, can be used with magnetic tape. On the basis of the second
method disk can be used. By the third method, the printer can be used. To do this
54

on a disc is established special area called SPOOL on which the output files to be
printed. This process is called SPOLLing.

27. OS Security management


Currently, there are several views of the threats of computer:
- Unauthorized access to a computer
- The problems of viruses and spam
The user who without authorization accesses the computer and with a view to
impair called a hacker. Viruses can cause the following types of damage:
1) Breaking work
2) disruption of important programs (eg, in Word may stop working some
functions);
3) a malfunction in the operating system;
4) possible destruction of information (files);
Viruses spread through the Internet and removable media. The operating system,
as a rule, there are no built-in antivirus tools. Currently, Microsoft distributes free
antivirus MS Security Essentials. To protect the unauthorized access to a computer
authentication procedure is used in the operating system (compulsory registration)
all the users choice and a password. Here, the main problem - is the strength of
passwords. They must be kept secretly and periodically updated. Passwords are
stored on your computer in a special encrypted format, making it difficult to find
them and use by unauthorized users. It is currently used authentication method based
on fingerprints.
The second method for controlling unauthorized access is called authorization
. For access to certain materials you need to have a permission . To do this, all users
are divided into groups according to their importance: a standard user, a user with
preference, a user with a high preference. For each group, and each category of
objects set access rules.
Object1 Object2 Object ... ObjectN
Group1 Read Write
Group2 Delete Open, Read Print
Group ... Delete
GroupN Write, Copy ...
55

With this method it is possible to restrict access to certain objects.


As known Windows use NTFS file system which support special services for
information security by limitations access to information for different categories of
users.
Windows support several (14) group of users. Most used Administrator, User,
Guest.
For any group Windows establish some rights and permissions to manage
information. Maximum –Administrator, minimum –Guest. Right it is ability to
do something on the computer. Permission it is
Permissions:

A permission is authorization to perform an operation on a


specific object, such as a file. Permissions are granted by
owners. If you own an object, you can grant any user or
security group permission to do whatever you are authorized to
do with it. This includes granting permission to take ownership.
User Rights:

A user right is authorization to perform an operation that


affects an entire computer rather than a specific object on the
computer.
It known that the term "rights" applies to users or groups of users
(such as "the user X has the right to change system time") and
the term "permissions" applies to an object (such as a folder or
file, e.g. "the user X has full permissions over this folder").
For any information object - folder and files Windows propose 6 standard
permissions ( folder and file different)
56

 28. OS programming tools.

To automate certain tasks in the operating system (primarily for administrators)


OS have special software, Ms Windows supports MS DOS bat-files (batch files), as
well as a special Windows Script Host (WSH) system, which includes a special
library objects and 2 programming language: VBScript and Jscript, with them you
can create scripts for OS management. With these software tools you can perform
tasks such as mass deleting files, downloading programs on schedule and many other
administrative tasks.
It is known that such tools were still in MS DOS. This command
or bat files. These files are created with a simple text
editor, NOTEPAD and must have the extension bat.
In the simplest case, these files represent a sequence of
commands Ms DOS (Lab 1). In more complex cases, they
may include an I / O command and control structure İF FOR
SET. Despite the fact that the bat can use files Ms Windows there is a
57

need for new programming tools. This is explained by the fact that the
batch files do not work with accommodation facilities such as shortcuts,
registry, etc..

29. Bat( batch) file language.Basics.


The first batch files (bat files) began to be used in MS-DOS. The MS Windows
they were further developed and applied. In other operating systems are similar
tools. In the simplest version of the bat file is a sequence of MS DOS
commands. The purpose of the bat files is to automate the execution of mass
operations, i.e. the launch of a single file, you can perform a variety of
operations. Bat file language very sensitive to space symbol –not use more then one
space !!!) Bat files have the .bat extension and are created in the editor notepad
(notebook). Consider the basic rules of programming bat files. The bat file text
constants are written without quotation marks.
'jafar' - wrong
Jafar - right
The bat file language is not case sensitive. There are 2 categories of
variables:
- Internal variables (stored inside, the symbol percentage -% jafar% - this is jafar
variable)
- Formal parameters. Transmitted in a bat file, they are written in the format % n
where n - number of the argument.
Additional parameters for the loop to be written as a name consisting of one character
and is written with two characters per cent ahead. (%% q)
Several commands are enclosed in braces may be written in a part of the for loop
statement.
Comments written in a bat file in text format rem
Rem group 628.5
Consider the main operators of the language:
Assignments text constant (set a = jafar)
Here jafar is text constant not variable !!!!!
58

Assignments numeric constant and formulas (set / A y = 5, set / A = 2 * 7-8)

In bat language are not mathematical


functions !!!!
Cleaning variable (set / A z =)

Input text SET /P variable=[promptString]

Set / p variable =[prompt]


Example
Set / p x = enter the group number

PAUSE the execution of a command file before pressing

@ echo off - disable output to screen trace of


implementation commands

Echo off command cancels the output of text on the screen.


@echo Off command cancels the text output of all commands, including echo and
himself too.

Example 1
@echo off
Set /p a=Enter a
set /p b= Enter b
set /a y=%a%+%b%
echo %y%
pause
59

To display using the echo command


echo jafar
echo % z%
EXAMPLE Output with comment
@echo off
Set /p a=Enter a
set /p b= Enter b
set /a y=%a%+%b%
set d=y=
set dd=%d%%y%
echo %dd%
pause

The output of that is:


60

EXAMPLE 3
@echo off
echo welcome to my calc
echo what is the num u wnt to insert to do
sum
set /p no1=
echo wt is the sec num
set /p no2=
set /a sum=%no1% + %no2%
echo %sum%

EXAMPLE 4
@echo off
Echo Type the first number you wish to add
set /p no1 add=
cls
Echo Type the second number you want to add to
the first number
set /p no2 add=
61

cls
echo Press any key to add the numbers
pause
set /a ans=%no1add%+%no2add%
echo %ans%
echo Press any key to return to the menu
pause

30. Batch file branching program.


The bat file language has a goto M operator where M is the label where the goto
statement refers. The label is written in the format m:
The if statement is written in the format:
For comparison, text constants:

IF [NOT] string1== string2 instruction

The variables and constants in the if statement should consist in double quotes
IF [/I] string1 comparizon operator string2 instruction

/I non case sensitive comparison


If string include digits it is consider as number
For example:
If "%a%" == "5af" goto m1
The following symbols are used to compare numerical data:
Equ =
Neq not equal
Lss <
Gtr >
Geq >=
Leq <=
62

If % t% equ 2 goto m8
There is a special version of the operator if.
Multiple commands in IF

if not exist MyFolderName (


ECHO create a folder
mkdir MyFolderName
)
1. Checking the existence of a file:
if exist jafar. doc goto m 2
If not exist jafar.doc goto m3
If errorlevel 1 goto m4

An example of the program


@echo off
Set b=Jafar
Echo %b%
If /I "%b%"=="JAFAR" goto m1
Echo not ok
Goto m2
: m1
Echo ok
: m2
Pause
Example 4
@echo off
Set /p a = enter a
Set /p b = enter b
Set /a y = %a%*2 +%b%*2
Echo %y%
If %a% GTR 3 goto m1
Echo not ok
Goto m2
: m1
63

Echo ok
: m2
Pause
Example 5
@echo off
REM math
Set /p a=enter a
Set /p b=enter b
Set /a y=%a%*2 + %b%*2
Echo %y%
if %y% GTR %a% goto m1
set /a z=%a%*%b%
echo %z%
goto m2
:m1
Set /a z=%a%+%b%
Echo %z%
:m2

@echo off
REM math
Set /p a=enter a
Set /p b=enter b
Set /a y=%a%*2 + %b%*2
Echo %y%
if %y% GTR %a% goto m1
set /a z=%a%*%b%
echo %z%
goto m2
:m1
Set /a z=%a%+%b%
Echo %z%
:m2
pause
if not exist MyFolderName (
64

ECHO create a folder


mkdir MyFolderName
)
31. Batch file loop program
Exist only FOR
2 variants

1)FOR /L %%parameter IN (start,step,end) DO


command

2) FOR /L %%parameter IN (list) DO command

Example 1
@echo off
for /L %% i in (1,1,10 ) do echo %% i

Example 2
65

@echo off
for %%A in (1 2 3 6 78 43) do echo %%A
pause

If cycle includes many operator use () ( in c/C++ {})

FOR %%A IN (1 2 3) DO (
echo %%A
)

FOR %%A IN (1 2 3) DO (
echo %%A
)
Example 2
for /L %%i in (1,1,10 ) do (
echo %%i
set /a j=6
echo %j
)
Example 3
for /L %%g in (1,1,10) do (
66

md folder%%g
md folder%%g\filesin
md folder%%g\filesout
)

Running multiple program ms at Bat files:


Example 4
Start / max Winword
Start / min Notepad
Start / max Excel

(Note that max -open in a maximized window; min - open in the minimized window)

32.WSH VBscript
We first look at the basics of programming in VBScript. The
program is typed in Notepad, and the extension vbs. The script runs on
the standard operation OPEN.
In this language, all data refer to the same type VARİANT.
Language is not case sensitive !!!!. Operators can be written on one
line, the separator is a symbol:.
Dim a, x, y
Are declared 3 variables.
To enter data is a special function InputBox ( "Comment"), this function
introduces only one variable
Array declaration and initialization
Dim a
a=array(5,7,8,12)

A = inputbox ( "enter a value of")


To output function is used
Msgbox "text" & variable.

Msgbox "answer =" &a

It is also possible Wscript.echo (a)

Arithmetic operations + - / * ^ ( an)


67

Concatenation strings &


Relation < > <= >= <> (not equal)
Logical operation AND OR NOT

List of basic mathematical functions


VB Mathematics
abs absolute value
acos arcos.
asin arsin.
atan arctan
cos cos
exp ex
sin sin
sqr square root.
tan tg
log ln

The assignment expression a =


Conditional operator
2. Simple İ F
If condition then
expression
End if
Full version
if condition then
1 expressions
else
2 expressions
end if

For loop operator

For i = a to b step h
expressions
next
68

While operator

While condition
expressions
wend
Example 1

Dim a, b, y
a=3
b=7
y = a^2 * b+2*sin(a-b)
Wscript.Echo (y)
Example 2

dim i,j
dim s
i=2
j=inputbox( "Enter j")
if 2*i+5<=3*j*j+6*j then
s=3*i*i+6*j
else
s=7*j+i
end if
WScript.Echo s

Example 3
dim a(5)
dim i, s
for i=1 to 5
a(i)=2*i^2-4
next
s=0
for i=1 to 5
if a(i)>7 then
s=s+a(i)
end if
next
Wscript.echo s

Example 4
69

dim a(5)
dim i, s
for i=1 to 5
a(i)=2*i-5
next
s=0
for i=1 to 5
if a(i)>2 then
s=s+a(i)
end if
next
Wscript.echo s
Example 5
dim a(5),b(5)
dim i, s
for i=1 to 5
a(i)=2
next
for i=1 to 5
b(i)=a(i)+1
next
s=0
for i=1 to 5
if i>2 then
s=s+a(i)+b(i)
end if
next
Wscript.echo s
Example 6

dim A
A=array(6,6,7,3)
dim s,i
s=0
for i=0 to 3
s=s+A(i)
next
MsgBox s
Example 7
dim a,b
a=array(3,5,6,7,2)
b=array (2,5,2,8,5)
70

dim i, s
s=0
for i=0 to 4
if i>2 then
s=s+a(i)+b(i)
end if
next
Wscript.echo s

Example 8
dim a
a=array(3,8,2,9,3)
dim i, s
s=0
for i=0 to 4
if a(i)>7 then
s=s+a(i)
end if
next
Wscript.echo s
Example 9
Dim a(3,3)
Dim i,j
a(0,0)=2
a(0,1)=3
a(0,2)=7
a(1,0)=2
a(1,1)=4
a(1,2)=7
a(2,0)=6
a(2,1)=4
a(2,2)=7
s=0
for i=0 to 2
for j=0 to 2
s=s+a(i,j)
next
next
MsgBox s

33. WSH Javascript


71

Javascript language similar to C ++. Extension js file. Language is


case sensitive. At the end of the operator is required; .
These are Declaration without TYPE
Declaration of variable var s;
1. Declaration of variable with initiliazation var s=7;
One dimensional array
1. Declaration of static array var a=[];
2. Declaration of static array with initialization var a=[5,7,8,12];

3. Declaration of dynamic array var a = new Array (10);


4. Declaration of dynamic array with initialization var b = new Array
(3,6,12,67) ;

2 dimensional array
Static
var d=[ [1,2], [3,4], [5,6]];
Dynamic
var a=new Array (5,6,3);
var b= new Array (6,6,7);
var c=[a,b];
var a=new Array(2,3,4);
var b=new Array (15,4,8);
var c=new Array(a,b);
var d =new Array ([4,7,6], [6,-4,2], [3,-9,10]); //matrix

3. Print data WScript.Echo (a);


Unfortunally in WSH Javascript absent operator for input data

Relation == Equal ! = (Not equal) > >= < <=


72

Logical operations and -&& or- || not !=


Text "my group"

Relations Equal to == ( double equ)) != (Not equal) > < >= <=
String “ my group”

i++ increment possible


i—decrement possible

If (condition)
{
Expressions 1;
}
else
{
Expressions 2;
}

for (i=0;i<=10;i++)
{
Expressions
}

while (condition)
{
Expressions
}

do
Expressions

while (condition)
73

When using mathematical functions is needed to


use Math.f syntax (x), for example Math.sin (x).
List of basic mathematical functions
abs absolute value
acos arcos.
asin arsin.
atan arctan
cos cos
exp exp
natural logarithm log
pow (x, n) degree pow (a, 5) -> a 5
sin sin
sqrt square root.
tg tan

.
Example 1

// first script
var a;
var b,y;
a=2; b=3;
y=a*b+12;
WScript.Echo (y);
Example 2
var i;
var s;
i=5;
if( 2*i*i-7*i+5>5)
s=i*i+5;
else
s=2*i-9*Math.sin(i);
WScript.Echo (s);

Example 3
var a=new Array (5);
var b=new Array (3,6,12,67);
var i;
74

a[0]=2; a[1]=7;a[2]=12;
for (i=0;i<=2;i++)
{WScript.Echo (a[i],b[i]);}

Example 4
var a= new Array (5);
var i;
var s;
for (i=0;i<=4;i++)
{a[i]=i;}
s=0;
for (i=0;i<=4;i++)
{
if (i>2)
s=s+3*Math.cos(a[i]);
}
WScript.Echo (s);

Example 5
var a= new Array (5);
var i;
var s;
for (i=0;i<=4;i++)
{a[i]=2*i;}
s=0;
for (i=0;i<=4;i++)
{
if (i>3)
s=s+3*a[i];
else
s=s+2*a[i];
}
WScript.Echo (s);

Example 6. Sum of matrix


var b = new Array ([4,7,6], [6,-4,2], [3,-9,10]);
var i,j;
var s=0;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
75

s=s+b[i][j];
WScript.Echo(s);
Example 7.
var a=[2,5,1,6,9];
var i;
var s;
s=0;
for (i=0;i<=4;i++)
{
if (i>2)
s=s+3*Math.cos(a[i]);
}
WScript.Echo (s);

34. Ms Windows scripting


Ms Windows programming tools are part of a special
component, WSH (Windows script host). WSH is composed of 2 parts
of the class library and two Vbscript and Jscript languages.
WSH includes the following class libraries:
1. File System Object to work with files and folders
2. WScript Object script execution, include methods such as Echo,
Sleep, Quit
3. WScript.Network Object Networking
4. WScript.Shell Object work with shortcuts, registry, system
information
Consider the example of two works with accommodation facilities WSH
Example 1. Create a file in VBScript

'VBScript Example
'create file system object
Set fs = CreateObject ( "Scripting.FileSystemObject" )
'create a new text file
Set TestFile = fs.CreateTextFile ( "c: \ jaf.txt", True)
'write a line into the test file
TestFile.WriteLine ( "Jafar is good student. ")
76

Example 2. Create file in WSH Javascript


// JScript example
var fs = new ActiveXObject ( "Scripting.FileSystemObject ");
var TestFile = fs.CreateTextFile ( "c: \\ vag2012.txt", true);
TestFile.WriteLine ( "This is a test. ");

Example 3. Create 50 word files in WSH Vbscript


' VBScript Exampl
dim a
dim b
dim c
dim i
a=inputbox("faylin adini ver")
b="e:\"&a
'create file system object
Set farida = CreateObject("Scripting.FileSystemObject")
'create a new text file
for i=1 to 50
c=b&cstr(i)&".docx"
Set TestFile = farida.CreateTextFile(c,True)
'write a line into the test file\
TestFile.WriteLine("This is a 609 group.")
next
Example 4 Create 50 folders
dim s
dim i
s=inputbox("adi daxil et")
ParentFolder = "E:\"
set objShell = CreateObject("Shell.Application")
set objFolder = objShell.NameSpace(ParentFolder)
for i=1 to 50
objFolder.NewFolder s&cstr(i)
77

next

Example 5. Square equation


dim a,b,c,x1,x2,d
a=inputbox("a daxil et")
b=inputbox("b daxil et")
c=inputbox("c daxil et")
d=b*b-4*a*c
if d>=o then
x1=(-b+d^(1/2))/(2*a)
x2=(-b-d^(1/2))/(2*a)
Msgbox "x1="&x1
Msgbox "x2="&x2
else
Msgbox "Helli yox"
end if

35.Mobile devices OS

A mobile operating system (mobile OS) is an OS built exclusively for a


mobile device, such as a smartphone, personal digital assistant (PDA),
tablet or other embedded mobile OS. Popular mobile operating systems
are Android, Symbian, iOS, BlackBerry OS and Windows Mobile.
A mobile OS is responsible for identifying and defining mobile device
features and functions, including keypads, application synchronization,
email, thumbwheel and text messaging. A mobile OS is similar to a
standard OS (like Windows, Linux, and Mac) but is relatively simple and
light and primarily manages the wireless variations of local and broadband
connections, mobile multimedia and various input methods.
With the exception of Android (developed by Google), mobile operating
systems are developed by different mobile phone manufacturers, including
Nokia (Symbian, MeeGo, Maemo); Apple (Apple iOS); Research In Motion
78

(RIM) (BlackBerry OS); Microsoft (Windows Mobile, Windows Phone) and


Samsung (Palm WebOS and bada).
Android, LiMo, Maemo, Openmoko and Qt Extended (Qtopia) are based on
the Linux open-source OS.
The Android OS consists of numerous Java applications and Java core
libraries running under the Java-based object oriented application
framework and the Dalvik Virtual Machine (VM). Dalvik is integral for the
Android to run in mobile devices as these systems are constrained in terms
of processor speed and memory.
As for multimedia support, the Android OS can back 2D and 3D graphics,
common audio and video formats. It may also support multi-touch input
(depending on device) and carries in its browser Google Chrome’s V8
JavaScript runtime.
IOS is a mobile operating system for Apple-manufactured devices. iOS
runs on the iPhone, iPad, iPod Touch and Apple TV.

iOS is best known for serving as the underlying software that allows iPhone
users to interact with their phones using gestures such as swiping, tapping
and pinching. These finger actions are typically performed on multitouch
capacitive touch screen displays, which provide fast response and accept
inputs from multiple fingers. Although it is not the No. 1 mobile OS globally,
iOS dominates the North American market by a large margin, with a 60
percent market share as of May 2010.
iOS is derived from Mac OS X and is a Unix-like OS. There are four
abstraction layers within iOS:
 Core OS Layer: Provides low-level features as well as
frameworks for security and interaction with external
hardware
 Core Services Layer: Provides services required by upper
layers
 Media Layer: Provides the necessary technologies for
graphics, audio and video.
 Coca Touch Layer: Where frameworks are located, which
are often used when creating an application
iOS comes with a lot of default apps, including an email client, a Safari
Web browser, a portable media player (iPod) and the phone app.
79

Developers can use the iOS software development kit (SDK) to create
applications for Apple mobile devices. The SDK includes tools and
interfaces for developing, installing, running and testing apps. Native apps
can be written using the iOS system frameworks and the Objective-C
programming language. Included in the iOS SDK are Xcode Tools, which
include an integrated development environment (IDE) for managing
application projects, a graphical tool for creating the user interface and a
debugging tool for analyzing runtime performance. It also includes an iOS
simulator, which allows developers to test apps on a Mac, and an iOS
developer library, which provides all the necessary documentation and
reference material.

36.UNIX
The history of UNIX began in the 60s. twentieth
century, when an employee of the Bell Labs
laboratory - the largest telecommunications
company in the world AT & T - Ken Thompson
wrote in the assembler language operating
system, which was jokingly named UNICS
(UNIPLEXED INFORMATION AND COMPUTING
SERVICE). Subsequently, the writing of this word
became shorter, turning into UNIX.
It's difficult to rewrite the entire assembly system for each new
machine, so Thompson decided to rewrite UNIX in a high-level
language, which he specifically designed and called B. But the
language B turned out to be inefficient, primarily because of the
lack of structures in it data. Then colleague Thompson Ritchie
developed the following language, which was the successor of the B
language, which, of course, was called C. Together, Thompson and
Ritchie rewrote UNIX in C. The language was just the language that
was needed at that time, and it retains the leading position in the
field of system programming so far. For the work on the creation of
UNIX Ritchie and Thompson by the association for computer
technology, ACM was awarded the prestigious Turing Award.
The UNIX operating system was supplied with a full set of source
code, so the owners of the system could improve it. New ideas and
system improvements were spreading quickly. By the mid-80's. The
80

UNIX OS was widely used on mini-computers and workstations of


various manufacturers. Many companies even purchased source
licenses to produce their versions of the UNIX system. One such
company was a small start-up company Microsoft, which for several
years was selling Version 7 under the name XENIX.
To ensure that the UNIX system could be guaranteed to run on any
machine, by the end of the 80's. With the assistance of the Standard
Boards Standards Council at the Institute of Electrical and
Electronics Engineers, IEEE attempted to combine the system
options. Hundreds of people from industrial, academic and
governmental organizations took part in this work. The collective
name of the project is POSIX.
The first three letters of this abbreviation meant the Portable
Operating System. The letters IX were added to make the project
name appear uniquely. The POSIX Committee has developed a
standard known as 1003.1. This standard defines a set of library
procedures that each UNIX-compliant system must provide, thus
ensuring that this program will run on any version of the system
that supports this standard.
The UNIX operating system can be viewed as a pyramid. At the
bottom of the pyramid is the hardware, consisting of CPU, memory,
disks, terminals and other devices. Above the hardware is the level
of the kernel mode of the UNIX system. Its function is to manage the
hardware and provide all programs with system calls. These system
calls allow programs to create processes and files and other
resources and manage them. Programs access system calls by
placing arguments in the CPU registers and executing interrupt
commands to switch from user mode to kernel mode and transfer
control to the UNIX operating system.
User mode levels are represented by a library of system calls and a
large number of standard programs (command processor,
compilers, editors, word processing programs, file utilities). It is
these programs that are launched by the user from the terminal.
Thus, there are three inter-layer interfaces in the UNIX operating
system: the system calls interface, the library functions interface,
and the interface formed by a set of standard service programs. The
latter interface is considered by most users to be a UNIX system. In
81

fact, it has almost no relation to the system itself and can easily be
replaced, for example, with a graphical interface, without requiring
any changes in the system itself. It was this flexibility that made the
UNIX system so popular and allowed it to survive numerous
changes in the technology underlying it. Many versions of the UNIX
system have a graphical user interface, similar to the popular
interfaces used on Macintosh computers and on the Windows
system.
The UNIX user interface consists not only of the shell, but also of a
large number of standard maintenance programs called utilities, as
well as a mass of application programs such as web browsers, image
viewers, etc.
UNIX processes are very similar to the consistent classical processes.
Each process runs one program and initially receives one control
thread.
UNIX is a multi-tasking system, so several independent processes
can work simultaneously. Each user can have several active
processes simultaneously, so that hundreds or even thousands of
processes can work simultaneously in a large system.
The UNIX file system is hierarchical, with files and directories. All
disks are mounted in a single directory tree, starting in one root.
Individual files can be associated with any tree directory.
Advantages
 Full multitasking with protected memory. Multiple users can
run multiple programs each at the same time without
interfering with each other or crashing the system.
 Very efficient virtual memory, so many programs can run with
a modest amount of physical memory.
 Access controls and security. All users must be authenticated
by a valid account and password to use the system at all. All
files are owned by particular accounts. The owner can decide
whether others have read or write access to his files.
 A rich set of small commands and utilities that do specific
tasks well -- not cluttered up with lots of special options. Unix
is a well-stocked toolbox, not a giant do-it-all Swiss Army
Knife.
82

 Ability to string commands and utilities together in unlimited


ways to accomplish more complicated tasks -- not limited to
preconfigured combinations or menus, as in personal
computer systems.
 A powerfully unified file system. Everything is a file: data,
programs, and all physical devices. Entire file system appears
as a single large tree of nested directories, regardless of how
many different physical devices (disks) are included.
 A lean kernel that does the basics for you but doesn't get in the
way when you try to do the unusual.
 Available on a wide variety of machines - the most truly
portable operating system.
 Optimized for program development, and thus for the unusual
circumstances that are the rule in research.
Disadvantages
 The traditional command line shell interface is user hostile --
designed for the programmer, not the casual user.
 Commands often have cryptic names and give very little
response to tell the user what they are doing. Much use of
special keyboard characters - little typos have unexpected
results.
 To use Unix well, you need to understand some of the main
design features. Its power comes from knowing how to make
commands and programs interact with each other, not just
from treating each as a fixed black box.
 Richness of utilities (over 400 standard ones) often overwhelms
novices. Documentation is short on examples and tutorials to
help you figure out how to use the many tools provided to
accomplish various kinds of tasks.
37. LİNUX

In 1991, Finnish student Linus Torvalds wrote another clone of


the UNIX system, which he called Linux. The first version of Linux
functionally did not differ from the micronuclear MINIX system.
83

However, unlike MINIX, Linux was a monolithic system, i.e. the


entire OS was placed in the kernel. The Linux operating system
quickly evolved and subsequently evolved into a full-fledged UNIX
clone with virtual memory, a more complex file system and many
other added functions. It was moved to other platforms and now
runs on a wide range of machines, like UNIX.
The Linux 1.0 version, introduced in 1994, included a new file
system, mapping files to the memory address space, and UNIX-
compatible network software. This version also included many new
device drivers. By that time, the Linux OS had become quite
compatible with UNIX, so a large number of UNIX software was
transferred to it, which greatly increased the usefulness of this
system. In addition, the Linux operating system attracted a large
number of developers who continued to work on its improvement
and expansion. The next version - 2.0, was released in 1996. It
included support for 64-bit architecture, symmetric multitasking,
new network protocols and many other functions. The system also
contained an impressive collection of different device drivers.
An unusual feature of Linux is its business model: it is free (free)
distributed software. This program, as well as distributions created
on its basis (installation kits including application programs) can be
downloaded from various Internet sites, for example,
www.kernel.org. The Linux system comes with a license developed
by Richard Stallman, the founder of the Free Software Foundation.
Components of Linux System
Linux Operating System has primarily three components
 Kernel − Kernel is the core part of Linux. It is responsible for
all major activities of this operating system. It consists of
various modules and it interacts directly with the underlying
hardware. Kernel provides the required abstraction to hide
low level hardware details to system or application programs.
 System Library − System libraries are special functions or
programs using which application programs or system
utilities accesses Kernel's features. These libraries implement
most of the functionalities of the operating system and do not
requires kernel module's code access rights.
84

 System Utility − System Utility programs are responsible to do


specialized, individual level tasks.

Kernel Mode vs User Mode


Kernel component code executes in a special privileged mode
called kernel mode with full access to all resources of the computer.
This code represents a single process, executes in single address
space and do not require any context switch and hence is very
efficient and fast. Kernel runs each processes and provides system
services to processes, provides protected access to hardware to
processes.
Support code which is not required to run in kernel mode is in
System Library. User programs and other system programs works
in User Mode which has no access to system hardware and kernel
code. User programs/ utilities use System libraries to access Kernel
functions to get system's low level tasks.
Basic Features
Following are some of the important features of Linux Operating
System.
 Portable − Portability means software can works on different
types of hardware in same way. Linux kernel and application
programs supports their installation on any kind of hardware
platform.
85

 Open Source − Linux source code is freely available and it is


community based development project. Multiple teams work
in collaboration to enhance the capability of Linux operating
system and it is continuously evolving.
 Multi-User − Linux is a multiuser system means multiple users
can access system resources like memory/ ram/ application
programs at same time.
 Multiprogramming − Linux is a multiprogramming system
means multiple applications can run at same time.
 Hierarchical File System − Linux provides a standard file
structure in which system files/ user files are arranged.
 Shell − Linux provides a special interpreter program which
can be used to execute commands of the operating system. It
can be used to do various types of operations, call application
programs. etc.
 Security − Linux provides user security using authentication
features like password protection/ controlled access to specific
files/ encryption of data.

GOOD LUCK !!

You might also like