Sie sind auf Seite 1von 71

NATIONAL INSTITUTE OF TECHNOLOGY, KURUKSHETRA

OPERATING SYSTEM LAB

Submitted By:

Name : Kulkin Goyat


Roll-No : 11510162
Section : CO-2
Semester : VI
Programme : Bachelor of Technology
Branch : Computer Engineering

1|Page
Table of Contents

1 Experiment 1 .......................................................................................................................................................4

1.1 Study of hardware and software requirement of various operating system .........................................................4

1.1.1 Window XP ............................................................................................................................................4

1.1.2 Windows 10............................................................................................................................................7

1.1.3 Window 8 ............................................................................................................................................. 10

1.1.4 UBUNTU ............................................................................................................................................. 12

1.1.5 UNIX .................................................................................................................................................... 15

1.1.6 Window 7 ............................................................................................................................................. 16

2.1 UNIX System Calls ........................................................................................................................................... 19

2 Experiment 2 : CPU Scheduling Policies ........................................................................................................ 20

2.1 FCFS ..........................................................................................................................................................20

2.2 SJF..............................................................................................................................................................22

2.3 Priority .......................................................................................................................................................25

2.4 Multi-level Queue ...................................................................................................................................... 28

3 Experiment 3 : File Storage Allocation Techniques ....................................................................................... 30

3.1 Contiguous(using array) ............................................................................................................................. 30

3.2 Linked-list(using linked list) ...................................................................................................................... 32

3.3 Indirect Allocation(using indexing) ........................................................................................................... 34

4 Experiment 4:Contiguous Allocation Techniques.......................................................................................... 36

4.1 Best Fit ....................................................................................................................................................... 36

4.2 First fit ........................................................................................................................................................ 40

4.3 Worst fit ........................................................................................................................................................ 44

5 Experiment 5 : External and Internal Fragmentation .................................................................................. 48

6 Experiment 6 : Compaction ............................................................................................................................. 50

7 Experiment 7 : Resource Allocation Graph ................................................................................................... 52

7.1 Using Adjacency Matrix ............................................................................................................................52

7.2 Using Adjacency List .................................................................................................................................53

8 Experiment 8 : Banker’s Algorithm ................................................................................................................ 55

9 Experiment 9 : Wait Graph ............................................................................................................................. 58

10 Experiment 10 : FORK and JOIN construct .................................................................................................. 60

2|Page
11 Experiment 11 : IPC-Semaphore .................................................................................................................... 63

11.1 Producer-Consumer Problem ................................................................................................................63

11.2 Reader-Writer Problem .............................................................................................................................. 65

11.3 Dining Philosopher Problem ......................................................................................................................69

3|Page
EXPERIMENT NO: 1

I. (a) Study of hardware and software requirements of different operating


systems
WINDOWS XP
Infrastructure

Windows XP uses prefetcher to improve startup and application launch times. It also became possible to revert the
installation of an updated device driver, should the updated driver produce undesirable results. The Prefetch is a component
of Microsoft Windows which was introduced in Windows XP. It is a component of the Memory Manager that can speed up
the Windows boot process and shorten the amount of time it takes to start up programs. It accomplishes this by caching files
that are needed by an application to RAM as the application is launched, thus consolidating disk reads and reducing disk
seeks.

Windows XP introduced a copy protection system known as Windows Product Activation. All Windows licenses must be tied
to a unique ID generated using information from the computer hardware, transmitted either via the internet or a telephone
hotline. If Windows is not activated within 30 days of installation, the OS will cease to function until it is activated. Windows
also periodically verifies the hardware to check for changes. If significant hardware changes are detected, the activation is
voided, and Windows must be re-activated.

Networking and internet functionality

Windows XP was originally bundled with Internet Explorer 6, Outlook Express 6, Windows Messenger, and MSN Explorer.

New networking features were also added, including Internet Connection Firewall, Internet Connection Sharing integration
with UPnP, Quality of Service features, IPv6.

Background Intelligent Transfer Service was also added which facilitates asynchronous, prioritized, and throttled transfer of
files between machines to deliver software updates to clients.

Also features like extended fax features, peer to peer networking, support for most DSL modems, IEEE 802.11 (Wi-Fi)
connections with auto configuration and roaming were added.

Remote Assistance and Remote Desktop were also added, which allow users to connect to a computer running Windows XP
from across a network or the Internet and access their applications, files, printers, and devices or request help.

Other Features

1. A number of kernel enhancements and power management improvements

2. Faster start-up, (due to improved Prefetch functions) logon, logoff, hibernation and application launch sequences.

3. Numerous improvements to increase the system reliability such as improved System Restore, Automated System
Recovery, Windows Error Reporting and driver reliability

4. Hardware support improvements such as USB 2.0 (with Service Pack 1)

4|Page
System requirements

Minimum Recommended

Home/Professional Edition

CPU

Pentium or compatible, 233 MHz Pentium or compatible, 300 MHz

BIOS or compatible firmware BIOS or compatible firmware

Memory

64 MB 128 MB

Hard drive

1.5 GB +661 MB for Service Pack 1 and 1a

+1.8 GB for Service Pack 2

+900 MB for Service Pack 3

Media

CD-ROM drive or compatible CD-ROM drive or compatible

Display

Super VGA (800 × 600) Super VGA (800 × 600)

Sound hardware

N/A Sound card plus speakers/headphones

Input device(s)

Keyboard, mouse Keyboard, mouse

Professional x64 Edition

CPU

x86-64 or compatible x86-64 or compatible

BIOS or compatible firmware[95] BIOS or compatible firmware[95]

Memory

256 MB 256 MB

Hard drive

5|Page
1.5 GB 1.5 GB

Master boot record used Master boot record used

Media

CD-ROM drive or compatible CD-ROM drive or compatible

Display

Super VGA (800 × 600) Super VGA (800 × 600)

Sound hardware

N/A Sound card plus speakers/headphones

Input device(s)

Keyboard, mouse Keyboard, mouse

Physical memory limits

The maximum amount of RAM that Windows XP can support varies depending on the product edition and the processor
architecture, as shown in the following table.

Physical memory limits of Windows XP

Edition Maximum

Starter 512 MB

Home 4 GB

Media Center "

Tablet PC "

Professional "

Professional x64 128 GB[106]

64-bit (Itanium) "

Editions

Windows XP was released in two major editions on launch: Home Edition and Professional Edition. Both editions were made
available at retail as pre-loaded software on new computers, and in boxed copies. Boxed copies were sold as "Upgrade" or
"Full" licenses. The "Upgrade" versions were slightly cheaper, but require an existing version of Windows to install. The "Full"
version can be installed on systems without an operating system or existing version of Windows. Both versions of XP were
aimed towards different markets: Home Edition is explicitly intended for consumer use and disables or removes certain
advanced and enterprise-oriented features present on Professional, such as the ability to join a Windows domain, Internet
Information Services, and Multilingual User Interface.

6|Page
WINDOWS 10
Features
Windows 10 is a personal computer operating system developed and released by Microsoft as part of the Windows NT
family of operating systems
It was released on July 29, 2015.
It is the first version of Windows that receives ongoing feature updates.
Windows 10 introduces what Microsoft described as "universal apps" ...these apps can be designed to run across multiple
Microsoft product families with nearly identical code?—?including PCs, tablets, smartphones, embedded systems, Xbox One,
Surface Hub and Mixed Reality.

The first release of Windows 10 also introduces a


1. virtual desktop system,
2. a window and desktop management feature called Task View,
3. the Microsoft Edge web browser,
4. support for fingerprint and face recognition login,
5. new security features for enterprise environments,
6. DirectX 12 and WDDM 2.0 to improve the operating system's graphics capabilities for games,
7. touch oriented interface was present.
8. capabilities of Cortana personal assistant and the
9. replacement of Internet Explorer with Microsoft Edge.

A new iteration of the Start menu is used on the Windows 10 desktop, with a list of places and other options on the left side,
and tiles representing applications on the right.

A feature known as Task View displays all open windows and allows users to switch between them, or switch between
multiple workspaces.

Windows Store apps, which previously could be used only in full screen mode, can now be used in self-contained windows
similarly to other programs.

Action Center, which displays notifications and settings toggles. It is accessed by clicking an icon in the notification area, or
dragging from the right of the screen.

Universal calling and messaging apps for Windows 10 are built in as of the November 2015 update: Messaging, Skype Video,
and Phone. These offer built-in alternatives to the Skype download and sync with Windows 10 Mobile.

Windows 10 is available in five main editions for personal computer devices, of which the Home and Pro versions are sold at
retail in most countries, and as pre-loaded software on new computers.

Home is aimed at home users,

while Pro is aimed at small businesses and enthusiasts.

7|Page
Each edition of Windows 10 includes all of the capabilities and features of the edition below it, and add additional features
oriented towards their market segments; for example, Pro adds additional networking and security features such as
BitLocker, Device Guard, Windows Update for Business, and the ability to join a domain.

The remaining editions, Enterprise and Education, contain additional features aimed towards business environments, and
are only available through volume licensing.

Windows 10 was considered "the best Windows yet" and was praised for having a better overall concept in its ability to be
"comfortable and effective" across a wide array of form factors, but that it was buggier than previous versions of Windows
were on-launch.

Security

Windows 10 incorporates multi-factor authentication technology based upon standards developed by the FIDO Alliance.

WINDOWS 10 operating system includes improved support for biometric authentication through the Windows Hello
platform. Devices with supported cameras (requiring infrared illumination) allow users to log in with iris or face recognition.
Devices with supported readers allow users to log in through fingerprint recognition.

Multi-factor authentication (MFA) is a method of computer access control in which a user is granted access only after
successfully presenting several separate pieces of evidence to an authentication mechanism – typically at least two of the
following categories: knowledge (something they know) and inherence (something they are).

Knowledge factors
Knowledge factors are the most commonly used form of authentication. In this form, the user is required to prove
knowledge of a secret in order to authenticate.A password is a secret word or string of characters that is used for user
authentication. This is the most commonly used mechanism of authentication.

Inherence factors
These are factors associated with the user, and are usually bio-metric methods, including fingerprint readers, retina scanners
or voice recognition.

FIDO:
The FIDO ("Fast IDentity Online") Alliance is an industry consortium launched in February 2013 to address the lack of
interoperability among strong authentication devices and the problems users face creating and remembering multiple
usernames and passwords. Nok Nok Labs, PayPal and Lenovo were among the founders.
FIDO's aim is that its specifications will support a full range of authentication technologies, including biometrics such as
fingerprint and iris scanners, voice and facial recognition, as well as existing solutions and communications standards, such
as Trusted Platform Modules (TPM), USB security tokensThe USB security token device may be used to authenticate using a
simple password (e.g. four-digit PIN) or by pressing a button.

The enterprise version of Windows 10 offers additional security features; administrators can set up policies for the automatic
encryption of sensitive data, selectively block applications from accessing encrypted data, and enable Device Guard—a
system which allows administrators to enforce a high security environment by blocking the execution of software that is not
digitally signed by a trusted vendor or Microsoft.

8|Page
Reliability

Battery life improvements. A performance power slider feature lets users easily switch between battery saver and best
performance mode levels, resulting in an average savings of 5 percent battery life. The Movies & TV app is more efficient,
resulting in a 5 percent battery life improvement while offline (and 2.5 percent while streaming). Improvements in Microsoft
Edge contributed a 17 percent improvement in battery life across every-day tasks, Microsoft says. And the Mail app is now
40 percent more efficient than it was in the November (2015) Update.

Performance improvements. Compared to the Anniversary Update (mid-2016), the Creators Update has provided a number
of performance improvements: 13 percent faster booting, 18 percent faster log-ins, 30 percent faster Windows Hello Facial
recognition, 53 percent faster browsing with Microsoft Edge, a faster Start Menu, faster Windows Search, and more.

Better reliability. In the Creators Update, Microsoft is seeing an 18 percent reduction in “users hitting certain system stability
issues versus earlier versions of Windows 10.” And there has been a 39 percent reduction in “operating system and driver
stability issues between the Anniversary Update and Creators Update.”

Reduced customer support volumes. According to data that does not include the time period before the incredibly buggy
Anniversary Update, it looks like Windows 10 customer support volume has “diminished significantly”. But there are no hard
numbers here. And I believe that Windows 10 was actually more reliable before the Anniversary Update as well.

Hardware Requirements

Microsoft lists the Windows 10 minimum hardware requirements as:


• Processor: 1 gigahertz (GHz) or faster processor or SoC
• RAM: 1 gigabyte (GB) for 32-bit or 2 GB for 64-bit
• Hard disk space: 16 GB for 32-bit OS 20 GB for 64-bit OS
• Graphics card: DirectX 9 or later with WDDM 1.0 driver
• Display: 800x600

Other factors:

•In reality, there are a number of factors that affect what hardware you really need. First, it depends whether you're
performing a clean installation or are upgrading from a previous Windows operating system. If you are performing an
upgrade, then the 16 GB -- or 20 GB for the 64-bit version -- of required hard disk space is inadequate; the existing OS
already takes up space.
•The Windows 10 minimum hardware requirements listed above only guarantee that the Windows operating system will
run. Applications typically have their own hardware requirements beyond those of the operating system.

Additional requirements to use certain features

• Cortana is only currently available on Windows 10 for the United States, United Kingdom, China, France, Italy, Germany,
Brazil, Mexico, Japan, Canada, Spain, Australia and India.
• Speech recognition will vary by device microphone. For a better speech experience, you will need a:
1 High fidelity microphone array
2. Hardware driver with microphone array geometry exposed
• windows Hello requires specialised illuminated infrared camera for facial recognition or a fingerprint reader which
supports the Windows Biometric Framework.

9|Page
• Continuum is available on all Windows 10 desktop editions by manually turning "tablet mode" on and off in the Action
Centre. It will be possible to configure tablets and 2-in-1s with GPIO indicators or those that have a laptop and slate indicator
to enter "tablet mode" automatically.
• Music and video streaming through Groove Music (formerly Xbox Music) or Films & TV apps is not available in all regions
• Xbox app requires an Xbox Live account, which is not available in all regions.
•Two factor authentication requires the use of a PIN, Biometric (fingerprint reader or illuminated infrared camera) or a
phone with Wi-Fi or Bluetooth capabilities.
•The number of applications that can be snapped will depend upon the minimum resolution for the application.
•To use touch, you need a tablet or a monitor that supports multi-touch.
•Microsoft account required for some features.
•Some games and programs might require a graphics card compatible with DirectX 10 or higher for optimal performance.
•BitLocker requires either Trusted Platform Module (TPM) 1.2, TPM 2.0 or a USB flash drive (Windows 10 Pro and Windows
10 Enterprise only).
•Client Hyper-V requires a 64-bit system with Second Level Address Translation (SLAT) capabilities and additional 2 GB of
RAM (Windows 10 Pro and Windows 10 Enterprise only).
•InstantGo works only with computers designed for Connected Standby.
•Device encryption requires a PC with InstantGo and TPM 2.0.
•Skype available only in select countries and regions.

WINDOWS 8
Features

Windows 8 is a personal computer operating system developed by Microsoft as part of the Windows NT family of operating
systems. Development of Windows 8 started before the release of its predecessor, Windows 7, in 2009. It was announced
at CES 2011, and followed by the release of three pre-release versions from September 2011 to May 2012. The operating
system was released to manufacturing on August 1, 2012, and was released for general availability on October 26, 2012.
Windows 8 introduced major changes to the operating system's platform and user interface to improve its user experience
on tablets, where Windows was now competing with mobile operating systems, including Android and iOS In particular,
these changes included a touch-optimized Windows shell based on Microsoft's "Metro" design language, the Start
screen(which displays programs and dynamically updated content on a grid of tiles), a new platform for developing "apps"
with an emphasis on touchscreen input, integration with online services (including the ability to synchronize apps and
settings between devices), and Windows Store, an online store for downloading and purchasing new software. Windows 8
added support for USB 3.0, Advanced Format hard drives, near field communications, and cloud computing. Additional
security features were introduced, such as built-in antivirus software, integration with Microsoft SmartScreen phishing
filtering service and support for UEFI Secure Boot on supported devices with UEFI firmware, to prevent malware from
infecting the boot process.
Windows 8 was released to a mixed critical reception. Although reaction towards its performance improvements, security
enhancements, and improved support for touchscreen devices was positive, the new user interface of the operating system
was widely criticized for being potentially confusing and difficult to learn, especially when used with a keyboard and mouse
instead of a touchscreen. Despite these shortcomings, 60 million Windows 8 licenses were sold through January 2013, a
number that included both upgrades and sales to OEMs for new PCs.
On October 17, 2013, Microsoft released Windows 8.1. It addressed some aspects of Windows 8 that were criticized by
reviewers and early adopters and incorporated additional improvements to various aspects of the operating
system. Windows 8 was ultimately succeeded by Windows 10 in July 2015. Support for Windows 8 RTM ended on January
12, 2016; per Microsoft lifecycle policies regarding service packs, Windows 8.1 must be installed to maintain support and
[10]
receive further updates.

Software Compatibility

10 | P a g e
The three desktop editions of Windows 8 support 32-bit and 64-bit architectures; retail copies of Windows 8 include install
DVDs for both architectures, while the online installer automatically installs the version corresponding with the architecture
[136][149]
of the system's existing Windows installation. The 32-bit version runs on CPUs compatible with x86 architecture 3rd
generation (known as IA-32) or newer, and can run 32-bitand 16-bit applications, although 16-bit support must be enabled
[150][151]
first. (16-bit applications are developed for CPUs compatible with x86 2nd generation, first conceived in 1978.
Microsoft started moving away from this architecture after Windows 95.
The 64-bit version runs on CPUs compatible with x86 8th generation (known as x86-64, or x64) or newer, and can run 32-bit
and 64-bit programs. 32-bit programs and operating system are restricted to supporting only 4 gigabytes of memory while
[152]
64-bit systems can theoretically support 2048 gigabytes of memory. 64-bit operating systems require a different set of
[152]
device drivers than those of 32-bit operating systems.
Windows RT, the only edition of Windows 8 for systems with ARM processors, only supports applications included with the
system (such as a special version of Office 2013), supplied through Windows Update, or Windows Store apps, to ensure that
the system only runs applications that are optimized for the architecture. Windows RT does not support running IA-32 or x64
[153]
applications. Windows Store apps can either support both the x86 and ARM architectures, or compiled to support a
specific architecture.

Hardware Requirement

The minimum system requirements for Windows 8 are slightly higher than those of Windows 7. The CPU must support
the Physical Address Extension (PAE), NX bit, and SSE2. Windows Store apps require a screen resolution of 1024×768 or
[116]
higher to run; a resolution of 1366×768 or higher is required to use the snap functionality. To receive certification,
Microsoft requires candidate x86 systems to resume from standby in 2 seconds or less.

Minimum hardware requirements for Windows 8[118]


Component Minimum Recommended
1 GHz clock rate x64 architecture
Processor IA-32 or x64 architecture Second Level Address Translation (SLAT) support
[119][120]
Support for PAE, NX and SSE2 for Hyper-V
IA-32 edition: 1 GB
Memory (RAM) 4 GB
x64 edition: 2 GB
DirectX 9 graphics device
Graphics Card DirectX 10 graphics device
WDDM 1.0 or higher driver
Display screen N/A 1024×768 pixels
Input device Keyboard and mouse multi-touch display screen
IA-32 edition: 16 GB
Hard disk space N/A
x64 edition: 20 GB
UEFI v2.3.1 Errata B with Microsoft Windows
Certification Authority in its database
Other N/A
Trusted Platform Module (TPM)
Internet connectivity

Microsoft's Connected Standby specification, which hardware vendors may optionally comply with, sets new power
consumption requirements that extend above the above minimum specifications. Included in this standard are a number of
security-specific requirements designed to improve physical security, notably against Cold Boot Attacks.
32-bit SKUs of Windows 8 only support a maximum of 4 GB of RAM. 64-bit SKUs, however support more: Windows 8 x64
supports 128 GB while Windows 8 Pro and Enterprise x64 support 512 GB
On March 18, 2016, in response to criticism from enterprise customers, Microsoft delayed the end of support and non-
critical updates for Skylake systems to July 17, 2018, but stated that they would also continue to receive security updates

11 | P a g e
through the end of extended support. On August 2016, Microsoft again extended the Skylake support policy to the date of
the end of extended support for Windows 7 (January 2020).
In January 2016, Microsoft announced that it would no longer support Windows 8.1 or 7 on devices using Intel's Skylake CPU
family effective July 17, 2018, and that all future CPU microarchitectures, as well as Skylake systems after this date, would
only be supported on Windows 10. After the deadline, only critical security updates were to be released for users on these
platforms. After this new policy faced criticism from users and enterprise customers, Microsoft partially retracted the change
and stated that both operating systems would remain supported on Skylake hardware through the end of their Extended
support lifecycle. Windows 8.1 remains officially unsupported on all newer CPU families, and neither AMD or Intel will
provide official chipset drivers for Windows operating systems other than Windows 10.

UBUNTU
[3]
Ubuntu (/ʊˈbʊntuː/; stylized as ubuntu) is an open source operating system for computers. It is a Linux distribution based
on the Debian architecture. It is usually run on personal computers, and is also popular on network servers, usually running
the Ubuntu Server variant, with enterprise-class features. Ubuntu runs on the most popular architectures, including Intel,
AMD, and ARM-based machines. Ubuntu is also available for tablets and smartphones, with the Ubuntu Touch edition.

[4]
Ubuntu is published by Canonical Ltd, who offer commercial support. It is based on free software and named after the
Southern African philosophy of ubuntu (literally, 'human-ness'), which Canonical Ltd. suggests can be loosely translated as
[3]
"humanity to others" or "I am what I am because of who we all are".

Ubuntu Desktop Edition

 2 GHz dual core processor.


 2 GiB RAM (system memory)
 25 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an alternative
approach)
 VGA capable of 1024x768 screen resolution.
 Either a CD/DVD drive or a USB port for the installer media.
 Internet access is helpful.

1. Better background process management.

Generally speaking, when a background process is enabled in Linux, the OS will only use it for as long as it needs to and then
disable it until needed again.

In Mac OS X, even though the OS is Unix-based, there are background processes that are “always on” in order to provide a
better GUI experience – and you can’t shut them off. With Linux you can shut everything off including the GUI and go straight
to a command prompt if you choose.

In Windows a long-standing complaint is the “always on” nature of many “services” that do nothing but eat away at system
resource and cause your computer to run slower for basically no reason.

GNU/Linux is also based on a modular design which contributes to its stability. This design means a "problem" in one part of
the system tends to be isolated from other parts of the system. For example, with GNU/Linux the Graphical User Interface
(GUI; the desktop part of the system you use with your mouse) is separated from the core operating system.

The ability to have total control over background processes is part of the reason Linux runs circles around OS X and Windows
in the speed department. It also adds stability.

12 | P a g e
Security

Ubuntu's goal is to be secure "out-of-the box". By default, the user's programs run with low privileges and cannot corrupt
the operating system or other users' files. For increased security, the sudo tool is used to assign temporary privileges for
performing administrative tasks, which allows the root account to remain locked and helps prevent inexperienced users from
[33]
inadvertently making catastrophic system changes or opening security holes. PolicyKit is also being widely implemented
[34]
into the desktop. Most network ports are closed by default to prevent hacking. A built-in firewall allows end-users who
[35]
install network servers to control access. A GUI (GUI for Uncomplicated Firewall) is available to configure it. Ubuntu
[36]
compiles its packages using GCC features such as PIE and buffer overflow protection to harden its software. These extra
[37]
features greatly increase security at the performance expense of 1% in 32-bit and 0.01% in 64-bit.

[38] [39]
Ubuntu also supports full disk encryption as well as encryption of the home and Private directories.

Variants

Ubuntu Server

A screenshot of the Ubuntu 12.04 Server installation boot menu

Ubuntu has a server edition that uses the same APT repositories as the Ubuntu Desktop Edition. The differences between
them are the absence of an X Window environment in a default installation of the server edition (although one can easily be
[111]
installed, including Unity, GNOME, KDE or Xfce), and some alterations to the installation process. The server edition uses
a screen-mode, character-based interface for the installation, instead of a graphical installation process. This enables
installation on machines with a serial or "dumb terminal" interface without graphics support.

Since version 10.10, the server edition (like the desktop version) supports hardware virtualization and can be run in a virtual
machine, either inside a host operating system or in a hypervisor, such as VMware ESXi, Oracle, Citrix XenServer, Microsoft
Hyper-V, QEMU, a Kernel-based Virtual Machine, or any other IBM PC compatible emulator or virtualizer. Ubuntu 7.10 and
later turn on the AppArmor security module for the Linux kernel by default on key software packages, and the firewall is
extended to common services used by the operating system.

 Has minimum requirements of: 512 MB RAM, 1 GHz CPU, and 1 GB disk space (1.75 GB for all features to be
[111]
installed).

[112]
Runs on all major architectures – x86, x86-64, ARM v7, ARM64, POWER8 and IBM System z mainframes via
[113]
LinuxONE. SPARC is no longer commercially supported.

[114][115][116]
Supports ZFS, a file system with snapshot capabilities, since Ubuntu 16.04 LTS.
 Has LXD, a hypervisor to manage LXC Linux containers.
 Includes the first production release of DPDK for line-speed kernel networking.
 Uses Linux 4.4 kernel and systemd service manager.

[113]
Is certified as a guest on AWS, Microsoft Azure, Joyent, IBM and HP Cloud.

It has up-to-date versions of key server software pre-installed, including: Tomcat (v8), PostgreSQL (v9.5), Docker v(1.10),
[113]
Puppet (v3.8.5), Qemu (v2.5), Libvirt (v1.3.1), LXC (v2.0), and MySQL (v5.6).

13 | P a g e
Ubuntu Touch

Ubuntu Touch is, by now, an unofficial version of Ubuntu developed for smartphones and tablets which was announced
[117]
then-official by Canonical on 2 January 2013. Ubuntu Touch was released to manufacturing on 16 September 2014. The
[118] [when?]
first device to run it was the Galaxy Nexus. A concept for a smartphone running Ubuntu for Phones was published
[119]
on Ubuntu's official channel on YouTube. The platform allows developing one app with two interfaces: a smartphone UI,
and, when docked, a desktop UI; a demo version for higher-end Ubuntu smartphones was shown that could run a full
[120]
Ubuntu desktop when connected to a monitor and keyboard, which was to ship as Ubuntu for Android. Ubuntu for
Tablets was previewed at 19 February 2013. According to the keynote video, an Ubuntu Phone will be able to connect to a
tablet, which will then utilize a tablet interface; plugging a keyboard and mouse into the tablet will transform the phone into
[121]
a desktop; and plugging a television monitor into the phone will bring up the Ubuntu TV interface.

On 6 February 2015, the first smartphone running Ubuntu Touch pre-installed was announced. The BQ Aquaris E4.5 Ubuntu
Edition features a 4.5-inch (110 mm) qHD display, a 1.3 GHz quad-core Cortex-A7 processor, and 1 GB of RAM. It is currently
[122]
priced at €169.90, while the 5-inch Aquaris E5 HD Ubuntu Edition is available for €199.90.

Mark Shuttleworth, Canonical CEO, announced on 5 April 2017, that Ubuntu Touch would no longer be developed by
[123] [124][125]
Canonical Ltd. The project was then picked up by the UBports community.

Cloud computing

Eucalyptus interface

Cloud Ubuntu Orange Box

14 | P a g e
Ubuntu offers Ubuntu Cloud Images which are pre-installed disk images that have been customized by Ubuntu engineering
[126]
to run on cloud-platforms such as Amazon EC2, OpenStack, Microsoft Windows and LXC. Ubuntu is also prevalent on VPS
[127]
platforms such as DigitalOcean.

Ubuntu 11.04 added support for OpenStack, with Eucalyptus to OpenStack migration tools added by Canonical in Ubuntu
[128][129]
Server 11.10. Ubuntu 11.10 added focus on OpenStack as the Ubuntu's preferred IaaS offering though Eucalyptus is
also supported. Another major focus is Canonical Juju for provisioning, deploying, hosting, managing, and orchestrating
enterprise data center infrastructure services, by, with, and for the Ubuntu Server.

UNIX
Software requirement :

1)Java Message Service and SOAP transport (Client requests and web service responses are transmitted as Simple Object
Access Protocol (SOAP) messages over HTTP to enable a completely interoperable exchange between clients and web
services, all running on different platforms and at various locations on the Internet.)

Required Software:
Java 2 SDK and Runtime Environment Version 5.0 or later.

On Linux: Apache Axis V1.4 provides support for SOAP and is shipped on the server DVD, but not installed.

STANDARD REQUIREMENT FOR AN OS TO BE TERMED AS A UNIX SYSTEM.

The Single UNIX Specification (SUS) is the collective name of a family of standards for computer operating systems,
compliance with which is required to qualify for using the "UNIX" trademark.

The core specifications of the SUS are developed and maintained by the Austin Group, which is a joint working group of IEEE,
and The Open Group.

If an operating system is submitted to The Open Group for certification, and passes conformance tests, then it is termed to
be compliant with a UNIX standard.

SECURITY AND FEATURES


It is often said that Linux and Mac, these two operating systems are the less vulnerable to virus attack. As these two systems
need advantaged access to install and run any kind of viruses. Even a well built Malware hardly can gain privileged or root
access to both these devices and that is why it seems difficult to influence a system’s vulnerability. LINUX install everything
from super computers to embedded processors as base cover. Though windows is the most recommended OS for desktop,
but the increasing occurrence of embedded devices is enhancing the popularity of Linux. People across the world are being
able to use it with any major support to minimize the attack of any Malware, especially when it is compared with windows.

Windows vs UNIX:

15 | P a g e
There are few people who believe that using UNIX as an operating system is safer option than using windows. However, it is
true that UNIX has something different to offer to its users, but the security quote that is available with the latest versions of
a windows should be get counted.

·Windows NT has been designed as a secure system with supplies for more security than what is implemented initially.
·Next generation secure computer basing, Service Pack of Windows XP, Windows 2003c security services all of these
provide an inspiring set of security mechanisms.
·Recent windows system offer maximum security ratings in comparison with UNIX and other operating system.

However, it is true that a majority of Windows user has faced several difficulties while operating both Microsoft and
windows, but this recent innovation may replace their experience with something exciting and secured as well.

Features:

Unix systems use a centralized operating system kernel which manages system and process activities. All non-kernel
software is organized into separate, kernel-managed processes.
Unix systems are preemptively multitasking: multiple processes can run at the same time, or within small time slices and
nearly at the same time, and any process can be interrupted and moved out of execution by the kernel. This is known as
thread management. Files are stored on disk in a hierarchical file system, with a single top location throughout the system
(root, or "/"), with both files and directories, subdirectories, sub-subdirectories, and so on below it.
With few exceptions, devices and some types of communications between processes are managed and visible as files or
pseudo-files within the file system hierarchy. This is known as everything is a file. However, Linus Torvalds states that this is
inaccurate and may be better rephrased as "everything is a stream of bytes".[1]

The UNIX operating system supports the following features and capabilities:

Multitasking and multiuser


Programming interface
Use of files as abstractions of devices and other objects
Built-in networking (TCP/IP is standard)
Persistent system service processes called "daemons" and managed by init or inet

WINDOWS 7
Introduction
[7]
Windows 7 (codenamed Vienna, formerly Blackcomb ) is a personal computer operating system developed by Microsoft. It
is a part of the Windows NT family of operating systems. Windows 7 was released to manufacturing on July 22, 2009, and
[8]
became generally available on October 22, 2009, less than three years after the release of its predecessor, Windows Vista.
Windows 7's server counterpart, Windows Server 2008 R2, was released at the same time.
Windows 7 was primarily intended to be an incremental upgrade to the operating system intending to address Windows
Vista's poor critical reception while maintaining hardware and software compatibility. Windows 7 continued improvements
on Windows Aero (the user interfaceintroduced in Windows Vista) with the addition of a redesigned taskbar that allows
applications to be "pinned" to it, and new window management features. Other new features were added to the operating
system, including libraries, the new file sharing system HomeGroup, and support for multitouch input. A new "Action Center"
interface was also added to provide an overview of system security and maintenance information, and tweaks were made to

16 | P a g e
the User Account Control system to make it less intrusive. Windows 7 also shipped with updated versions of several stock
applications, including Internet Explorer 8, Windows Media Player, and Windows Media Center.
In contrast to Windows Vista, Windows 7 was generally praised by critics, who considered the operating system to be a
major improvement over its predecessor due to its increased performance, its more intuitive interface (with particular praise
devoted to the new taskbar), fewer User Account Control popups, and other improvements made across the platform.
Windows 7 was a major success for Microsoft; even prior to its official release, pre-order sales for 7 on the online
retailer Amazon.com had surpassed previous records. In just six months, over 100 million copies had been sold worldwide,
increasing to over 630 million licenses by July 2012, and a market share of 43.08% of "desktop operating systems" as of
[9]
December 2017 according to Net Applications, making it the most widely used version of Windows (while Windows 10 is
now more popular in Europe and North America).

New and changed


[42]
Among Windows 7's new features are advances in touch and handwriting recognition, support for virtual hard
[43] [44][45][46][47]
disks, improved performance on multi-core processors, improved boot performance, DirectAccess,
and kernel improvements. Windows 7 adds support for systems using multiple heterogeneous graphics cards from different
[48] [49]
vendors (Heterogeneous Multi-adapter), a new version of Windows Media Center, a Gadgetfor Windows Media Center,
[50] [51]
improved media features, XPS Essentials Pack and Windows PowerShell being included, and a
redesigned Calculatorwith multiline capabilities including Programmer and Statistics modes along with unit conversion for
[52]
length, weight, temperature, and several others. Many new items have been added to the Control Panel,
[53] [54]
including ClearType Text Tuner Display Color Calibration Wizard, Gadgets, Recovery, Troubleshooting, Workspaces
[55]
Center, Location and Other Sensors, Credential Manager, Biometric Devices, System Icons, and Display. Windows Security
Center has been renamed to Windows Action Center (Windows Health Center and Windows Solution Center in earlier
builds), which encompasses both security and maintenance of the computer. ReadyBoost on 32-bit editions now supports up
to 256 gigabytes of extra allocation. Windows 7 also supports images in RAW image format through the addition of Windows
Imaging Component-enabled image decoders, which enables raw image thumbnails, previewing and metadata display in
[56]
Windows Explorer, plus full-size viewing and slideshows in Windows Photo Viewer and Windows Media Center. Windows
7 also has a native TFTP client with the ability to transfer files to or from a TFTP server.

The default taskbar of Windows 7.

Physical memory
The maximum amount of RAM that Windows 7 supports varies depending on the product edition and on the processor
[102]
architecture, as shown in the following table.

Physical memory limits of Windows 7

Processor architecture
Edition
IA-32 (32-bit) x64 (64-bit)
Ultimate
Enterprise 192 GB
4 GB
Professional
Home Premium 16 GB

17 | P a g e
Home Basic 8 GB
Starter 2 GB N/A

Processor limits
[103]
Windows 7 Professional and up support up to 2 physical processors (CPU sockets), whereas Windows 7 Starter, Home
[104]
Basic, and Home Premium editions support only 1. Physical processors with either multiple cores, or hyper-threading, or
both, implement more than one logical processor per physical processor. The x86 editions of Windows 7 support up to 32
[105]
logical processors; x64 editions support up to 256 (4 x 64).

Security in Windows

Windows-based operating systems have always been plagued with a host of security flaws and vulnerabilities, this is mainly
because the systems were not designed with secure computing in mind. They are also a popular target for hackers due to
these flaws. In today’s increasingly connected world we cannot allow our systems to be compromised without dire
consequences. Windows 7 has tried to address these issues by following a Secure Development Life Cycle (SDLC), i.e.
developers enforced a strict code review of all new code and they performed refactoring and code review of older OS
code.Several of the major security improvements are given below in greater detail.

1. Date Execution Prevention (DEP)

During the execution of a process, it will contain several memory locations that do not contain executable code. Attackers
use these sections to initiate code injection attacks. After arbitrary code has been inserted, they can carry out attacks such as
buffer overflows. Data Execution Prevention is a security technique that is used to prevent the execution of code from such
data pages. This is done by marking data pages as non-executable. This makes it harder for code to be run in those memory
locations.

DEP is intended to be used with other mechanisms such as ASLR and SEHOP. When used together, it makes it very difficult
for attacks to exploit the application using memory attacks. DEP support, though present in Windows 7, is opt-in, i.e. it is not
enabled by default, but users are encouraged to enable DEP support.

DEP can be enabled system wide or on a per application basis. This is configured by the system administrator.

DEP types
There are two DEP implementations:

 Hardware enforced DEP


 Software enforced DEP
Hardware enforced DEP marks all memory locations as non-executable by default unless the location contains executable
code explicitly. This helps prevent attacks that try to insert code from non-executable memory locations.
Hardware DEP makes use of processor hardware to mark memory as non-executable, this is done by setting an attribute at
the specified memory location. Hardware enforced DEP requires the system to be using a DEP compatible processor. Both
AMD and Intel have both released processors with DEP support.

 AMD based processors make use of the NX bit to signify non-executable sections of memory.
 Intel based processors make use of the XD (Execute disable) bit to signify the same.

18 | P a g e
b) UNIX system calls
Process control System Calls in UNIX

 fork() : To create a new process


 exec() : To execute a new program in a process
 wait() : To wait until a created process completes its execution
 exit() : To exit from a process execution
 getpid() : To get a process identifier of the current process
 getppid() : To get parent process identifier
 nice() : To bias the existing priority of a process
 kill() : To kill a process
 brk() : To increase/decrease the data segment size of a process

File management System Calls in UNIX

 open() : system call to open a file


 close() : system call to close a file
 read() : read data from a file opened for reading
 write() : write data to a file opened for writing
 lseek() : seek to a specified position in a file
 create(): create a file
 link()/unlink() : create or remove hard-link to a file

Input-Output System Calls in UNIX

 read(): read data from device


 open() : system call to open a device
 close() : system call to close a device

19 | P a g e
EXPERIMENT 2: CPU Scheduling Policies
I ) Implementing CPU Job Scheduling Policies

a) First Come First serve


#include<bits/stdc++.h>
using namespace std;
int numberOfProcess;
struct Process
{
int pId;
int arrivalTime;
int burstTime;
};
int myCmp(const void* l1,const void* l2)
{
Process p1 = *(Process*)l1;
Process p2 = *(Process*)l2;
if(p1.arrivalTime>p2.arrivalTime)
return 1;
else if(p1.arrivalTime==p2.arrivalTime&&p1.burstTime>p2.burstTime)
return 1;
else
return -1;
}
int main()
{
cout<<"enter Number of Process:\t";
cin>>numberOfProcess;
Process process[numberOfProcess];
cout<<"enter details:\n";
cout<<"Id\tB.T\tA.T"<<endl;
for(int i = 0;i<numberOfProcess;i++)
{
cout<<i+1<<"\t";
process[i].pId = i+1;
cin>>process[i].burstTime;
cin>>process[i].arrivalTime;
}
Process result[numberOfProcess];
cout<<"\nprocess will be executed in following order:\n";
qsort((void*)process,numberOfProcess,sizeof(Process),myCmp);
for(int i = 0;i<numberOfProcess;i++)
result[i] = process[i];
cout<<"Id\tB.T\tA.T\tW.T\tT.A"<<endl;
int time_taken = 0;
int tWT = 0;
int tTA = 0;
for(int i = 0;i<numberOfProcess;i++)
{

20 | P a g e
cout<<result[i].pId<<"\t";
cout<<result[i].burstTime<<"\t";
cout<<result[i].arrivalTime<<"\t";
if(i==0)
cout<<"0\t";
else
{
cout<<time_taken-result[i].arrivalTime<<"\t";
tWT+=time_taken-result[i].arrivalTime;
}
time_taken+=result[i].burstTime;
cout<<time_taken-result[i].arrivalTime<<endl;
tTA+=time_taken-result[i].arrivalTime;
}
cout<<"avg waiting time:\t"<<(float)tWT/numberOfProcess<<endl;
cout<<"avg turn Around time:\t"<<(float)tTA/numberOfProcess;
}

21 | P a g e
b) Shortest Job First
#include<bits/stdc++.h>
using namespace std;
int numberOfProcess;
struct Process
{
int pId;
int arrivalTime;
int burstTime;
};
int myCmp(const void* l1,const void* l2)
{
Process p1 = *(Process*)l1;
Process p2 = *(Process*)l2;
if(p1.arrivalTime>p2.arrivalTime)
return 1;
else if(p1.arrivalTime==p2.arrivalTime&&p1.burstTime>p2.burstTime)
return 1;
else
return -1;
}

Process findNextProcess(Process process[],int* time_so_far)


{
int Min=INT_MAX;
Process temp ;
int z = 0;
for(int i = 0;i<numberOfProcess;i++)
{
if(process[i].arrivalTime<=*time_so_far)
{
if(process[i].burstTime<Min)
{
Min = min(Min,process[i].burstTime);
temp = process[i];
z = i;
}
}
}
*time_so_far+=temp.burstTime;
process[z].burstTime = INT_MAX;
return temp;
}
int main()
{
cout<<"enter Number of Process:\t";
cin>>numberOfProcess;

Process process[numberOfProcess];

22 | P a g e
cout<<"enter details:\n";
cout<<"Id\tB.T\tA.T"<<endl;

for(int i = 0;i<numberOfProcess;i++)
{
cout<<i+1<<"\t";
process[i].pId = i+1;
cin>>process[i].burstTime;
cin>>process[i].arrivalTime;
}

Process result[numberOfProcess];

cout<<"\nprocess will be executed in following order:\n";

qsort((void*)process,numberOfProcess,sizeof(Process),myCmp);

result[0] = process[0];
process[0].burstTime = INT_MAX;

int time_so_far = result[0].burstTime;

for(int i = 1;i<numberOfProcess;i++)
{
result[i] = findNextProcess(process,&time_so_far);
}

cout<<"Id\tB.T\tA.T\tW.T\tT.A"<<endl;

int time_taken = 0;

int tWT = 0;
int tTA = 0;

for(int i = 0;i<numberOfProcess;i++)
{
cout<<result[i].pId<<"\t";
cout<<result[i].burstTime<<"\t";
cout<<result[i].arrivalTime<<"\t";

if(i==0)
cout<<"0\t";
else
{
cout<<time_taken-result[i].arrivalTime<<"\t";
tWT+=time_taken-result[i].arrivalTime;
}

time_taken+=result[i].burstTime;
cout<<time_taken-result[i].arrivalTime<<endl;
tTA+=time_taken-result[i].arrivalTime;

23 | P a g e
}

cout<<"avg waiting time:\t"<<(float)tWT/numberOfProcess<<endl;


cout<<"avg turn Around time:\t"<<(float)tTA/numberOfProcess;

24 | P a g e
c) Priority Scheduling
#include<bits/stdc++.h>
using namespace std;

int numberOfProcess;
struct Process
{
int pId;
int arrivalTime;
int burstTime;
int priorityValue;
};

bool myCmp(Process p1,Process p2)


{
if(p1.arrivalTime<p2.arrivalTime)
return true;
else if(p1.arrivalTime==p2.arrivalTime&&p1.priorityValue<p2.priorityValue)
return true;
else if(p1.arrivalTime==p2.arrivalTime&&p1.priorityValue==p2.priorityValue&&p1.burstTime<p2.burstTime)
return true;
else
return false;
}

Process findNextProcess(Process process[],int* time_so_far)


{
int Min=INT_MAX;
Process temp ;
int z = 0;

for(int i = 0;i<numberOfProcess;i++)
{
if(process[i].arrivalTime<=*time_so_far)
{
if(process[i].priorityValue<Min)
{
Min = min(Min,process[i].priorityValue);
temp = process[i];
z = i;
}
}
}

*time_so_far+=temp.burstTime;
process[z].priorityValue = INT_MAX;
return temp;
}

int main()

25 | P a g e
{
cout<<"enter Number of Process:\t";
cin>>numberOfProcess;

Process process[numberOfProcess];

cout<<"enter details:\n";
cout<<"Id\tB.T\tA.T\tP.V"<<endl;

for(int i = 0;i<numberOfProcess;i++)
{
cout<<i+1<<"\t";
process[i].pId = i+1;
cin>>process[i].burstTime;
cin>>process[i].arrivalTime;
cin>>process[i].priorityValue;
}

Process result[numberOfProcess];
cout<<"\nprocess will be executed in following order:\n";

sort(process,process+numberOfProcess,myCmp);

result[0] = process[0];
process[0].priorityValue = INT_MAX;

int time_so_far = result[0].burstTime;

for(int i = 1;i<numberOfProcess;i++)
result[i] = findNextProcess(process,&time_so_far);

cout<<"Id\tB.T\tA.T\tP.V\tW.T\tT.A"<<endl;

int time_taken = 0;

int tWT = 0;
int tTA = 0;

for(int i = 0;i<numberOfProcess;i++)
{
cout<<result[i].pId<<"\t";
cout<<result[i].burstTime<<"\t";
cout<<result[i].arrivalTime<<"\t";
cout<<result[i].priorityValue<<"\t";
if(i==0)
cout<<"0\t";
else
{
cout<<time_taken-result[i].arrivalTime<<"\t";
tWT+=time_taken-result[i].arrivalTime;
}

26 | P a g e
time_taken+=result[i].burstTime;
cout<<time_taken-result[i].arrivalTime<<endl;
tTA+=time_taken-result[i].arrivalTime;
}

cout<<"avg waiting time:\t"<<(float)tWT/numberOfProcess<<endl;


cout<<"avg turn Around time:\t"<<(float)tTA/numberOfProcess;
}

27 | P a g e
d) Multi-level feedback queue scheduling
#include<stdio.h>
struct proc
{
int arr,arr1,bst,bst1,que,id;
} p[10],q[10];
int main()
{
printf("----multi level queue scheduling---- \n");
int i,j,k,n,t[10],w[10];
static int s=0;
float sum_t=0,sum_w=0;

for(i=0;i<10;i++)
q[i].bst=-1;
printf("enter no of processes\t\t");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i].id=i;
printf("enter arrival time\t\t\t");
scanf("%d",&p[i].arr);
p[i].arr1=p[i].arr;
printf("Enter brust time\t\t\t");
scanf("%d",&p[i].bst1);
p[i].bst=p[i].bst1;
printf("enter queue no 0(high priority) or 1\t");
scanf("%d",&p[i].que);
}
int m=0,l=0,count=0;
for(k=0;count<5;k++)
{
for(j=0;j<n;j++)
{
if(p[j].arr==k)
{
if(p[j].que==0)
{
int h=m;
while(h>l)
{
q[h]=q[h-1];
h--;
}
q[l]=p[j];
m++;
l++;
}
else
{

28 | P a g e
q[m]=p[j];
m++;
}
p[j].arr=9999;
}
}
for(j=0;j<s;j++)
{
if(q[j].bst!=0)
{
s=j;
break;
}
}
while(q[s].bst==0)
s++;
if(q[s].bst>0)
q[s].bst--;
if(q[s].bst==0)
{
t[s]=k-q[s].arr1+1;
w[s]=t[s]-q[s].bst1;
sum_t=sum_t+t[s];
sum_w=sum_w+w[s];
printf("\nturn arround time of p%d is %d and is wait time is %d\n",q[s].id,t[s] ,w[s]);
s++;
}
if(q[s].bst==-1)
count++;
}
printf("\naverage turn arround time is %f",sum_t/n);
printf("\naverage wait time is %f",sum_w/n);
return 0;}

29 | P a g e
EXPERIMENT 3: FILE STORAGE ALLOCATION TECHNIQUES
I) Implementing File Storage Allocation Techniques

a) Contiguous (Using Array)


#include<stdio.h>
int start[20],temp[20],end[20],count,max=10000;
char n[20][20];
void display(int k);
int main()
{
int i,j;
int a[10000]={0};
int ch=1,k=1;
n[0][0]='O';n[0][1]='S';temp[0]=500;start[0]=0;end[0]=499;for(j=0;j<500;j++){a[j]=1; }
display(k);
while(ch)
{
printf("\nenter file name\t");
scanf("%s",n[k]);
printf("enter size of file\t");
scanf("%d",&temp[k]);
for(i=0;i<max;i++)
{
count=0;
if(a[i]==0)
{
start[k]=i;
count=0;
while(a[i]==0)
{
count++;
if(count==temp[k])
{
end[k]=i;
break;
}
i++;
}
}
if(count==temp[k])
{
for(j=start[k];j<=end[k];j++)
{
a[j]=1;
}
k++;
break;
}

30 | P a g e
else if(i>max-2)
{
printf("\nOut of memory");
}
}
display(k);
printf("\npress 0 to exit and 1 for continue entering file\n");
scanf("%d",&ch);
}
}
void display(int k)
{
int i,sum=0;;
printf("*****MEMORY MAP*****");
printf("\nFILENAME SIZE BLOCKS ALLOCATED");
for(i=0;i<k;i++)
{
printf("\n%s %d %d-%d",n[i],temp[i],start[i],end[i]);
sum=sum+temp[i];
}
printf("\nFREE DISK SPACE %d\n",max-sum);
}

31 | P a g e
b) Linked-list (using linked list)
#include<stdio.h>
#include<stdlib.h>

struct node
{
int num;
struct node * next;
};
int temp[20],end[20],count,max=100; char n[20][20];
void display(int k); node * getnode()
{
return ((struct node *)malloc(sizeof(struct node)));
}
struct node *start[20], *curr; int main()
{
int i,j;
printf("total space %d",max); int a[100]={0};
int ch=1,k=1; n[0][0]='O';n[0][1]='S';temp[0]=10;
int flag=0; for(j=0;flag<10;j++)
{
int x=rand()%30; if(j==0)
{
start[0]=getnode(); start[0]->num=x; start[0]->next=NULL; curr=start[0];
a[x]=1;
flag++;
}
if(a[x]==0 && j!=0)
{
curr->next=getnode(); curr=curr->next;
curr->num=x; curr->next=NULL; a[x]=1;
flag++;
}
}
display(k);
while(ch)
{
printf("\nenter file name"); scanf("%s",n[k]); printf("enter size of file"); scanf("%d",&temp[k]);
count=0; for(i=0;i<max;i++)
{
if(a[i]==0 && count==0)
{
start[k]=getnode(); start[k]->num=i; start[k]->next=NULL; count++; curr=start[k];
a[i]=1;
}
if(a[i]==0)
{
curr->next=getnode(); curr=curr->next;
curr->num=i; curr->next=NULL; count++;
a[i]=1;

32 | P a g e
}
if(count==temp[k])
{
k++;
break;
}
}
display(k);
printf("\ndo you want to continue"); scanf("%d",&ch);
}
}
void display(int k)
{
int i,sum=0;;
printf("\n *****MEMORY MAP*****");
printf("\nFILENAME SIZE STARTING BLOCK Allocated blocks"); for(i=0;i<k;i++)
{
printf("\n%s %d %d ",n[i],temp[i],start[i]->num);

struct node *curr=start[i]; while(curr!=NULL)


{
printf("%d ",curr->num); curr=curr->next;
}
sum=sum+temp[i];
}
printf("\nFREE DISK SPACE %d",max-sum);
}

33 | P a g e
c) Indirect Allocation (Indexing)
#include<stdio.h>
#include<stdlib.h>
struct node
{
int num;
struct node * next;
};
int temp[20],end[20],count,max=100,*INDEX[10],sum=0; char n[20][20];
void display(int k);
node * getnode()
{
return ((struct node *)malloc(sizeof(struct node)));
}
struct node *start[20], *curr; int main()
{
int i,j,ADD[100];
printf("total space %d",max); int a[100]={0};
int ch=1,k=1; n[0][0]='O';n[0][1]='S';temp[0]=10;
int flag=0; printf("1"); for(j=0;flag<10;j++)
{
int x=rand()%20; if(j==0)
{
INDEX[0]=&ADD[sum];
start[0]=getnode(); start[0]->num=x; start[0]->next=NULL; curr=start[0]; ADD[flag]=x;
a[x]=1;
flag++;
}
if(a[x]==0 && j!=0)
{
curr->next=getnode(); curr=curr->next;
curr->num=x; curr->next=NULL; a[x]=1;
ADD[flag]=x; flag++;
}
}
display(k); while(ch)
{
printf("\nenter file name\t"); scanf("%s",n[k]); printf("enter size of file\t"); scanf("%d",&temp[k]);
count=0; int m=0;
printf("\nADD%d\n",ADD); for(i=0;i<max;i++)
{
if(a[i]==0 && count==0)
{
INDEX[k]=&ADD[sum];
start[k]=getnode(); start[k]->num=i; start[k]->next=NULL; count++; curr=start[k];
a[i]=1;
ADD[sum+m]=i; m++;
}
if(a[i]==0)

34 | P a g e
{
curr->next=getnode(); curr=curr->next;
curr->num=i; curr->next=NULL; count++;
a[i]=1;
ADD[sum+m]=i; m++;
}
if(count==temp[k])
{
k++;
break;
}
}
display(k);
printf("\ndo you want to continue"); scanf("%d",&ch);
}
}
void display(int k)
{
int i,j;
printf("\n *****MEMORY MAP*****"); printf("\nFILENAME SIZE INDEX Allocated blocks");
for(i=0;i<k;i++)
{
printf("\n%s %d %d ",n[i],temp[i],i); for(j=0;j<temp[i];j++)
{
printf("%d ",*(*(INDEX+i)+j));
}
sum=sum+temp[i];
}
printf("\nFREE DISK SPACE %d",max-sum);
}

35 | P a g e
EXPERIMENT 4: CONTIGUOS ALLOCATION TECHNIQUES
a) BEST FIT

i) Fixed Allocation
#include<bits/stdc++.h>
using namespace std;

/*
zero based Indexing is there in Partition And Result
*/

int findBestPossiblePartition(int processSize,bool used[],int partition[],int numberOfPartition)


{
int res = -1;
int partitionNumber = -1;
int minSize =INT_MAX;
for(int i = 0;i<numberOfPartition;i++)
{
if(used[i]==true) continue;
if(partition[i]>=processSize)
{
if(partition[i]<minSize)
{
minSize = partition[i];
partitionNumber = i;
}
}
}
return partitionNumber;
}
int main()
{
int numberOfPartition;
cout<<"Enter the number of available Partitions:-\t";
cin>>numberOfPartition;

int partition[numberOfPartition];
cout<<"Enter the Available Partition Space:-\t";

bool used[numberOfPartition] = {false};

for(int i = 0;i<numberOfPartition;i++)
cin>>partition[i];

int numberOfProcess;
cout<<"Enter the number of Process:-\t";
cin>>numberOfProcess;

int processSize[numberOfProcess];

36 | P a g e
cout<<"Enter the Process Size:-\t";

for(int i = 0;i<numberOfProcess;i++)
cin>>processSize[i];

int resultBlock[numberOfProcess] ;
memset(resultBlock,-1,sizeof(resultBlock));

int result;
for(int i = 0;i<numberOfProcess;i++)
{
result = findBestPossiblePartition(processSize[i],used,partition,numberOfPartition);
resultBlock[i] = result;
used[result] = true;
}
for(int i = 0;i<numberOfProcess;i++)
cout<<"Process No: "<<i<<"\tAllocated Partition:\t"<<resultBlock[i]<<endl;

37 | P a g e
II). Best Fit Variable Allocation

#include<bits/stdc++.h>
using namespace std;

/*
zero based Indexing is there in Partition And Result
*/

int findBestPossiblePartition(int processSize,int partition[],int numberOfPartition)


{
int res = -1;

int partitionNumber = -1;


int minSize =INT_MAX;

for(int i = 0;i<numberOfPartition;i++)
{
if(partition[i]>=processSize)
{
if(partition[i]<minSize)
{
minSize = partition[i];
partitionNumber = i;
}
}
}

if(partitionNumber!=-1)
partition[partitionNumber] -= processSize;
return partitionNumber;
}

int main()
{
int numberOfPartition;
cout<<"Enter the number of available Partitions:-\t";
cin>>numberOfPartition;

int partition[numberOfPartition];
cout<<"Enter the Available Partition Space:-\t";

for(int i = 0;i<numberOfPartition;i++)
cin>>partition[i];

int numberOfProcess;
cout<<"Enter the number of Process:-\t";
cin>>numberOfProcess;

int processSize[numberOfProcess];
cout<<"Enter the Process Size:-\t";

38 | P a g e
for(int i = 0;i<numberOfProcess;i++)
cin>>processSize[i];

int resultBlock[numberOfProcess] ;
memset(resultBlock,-1,sizeof(resultBlock));

int result;
for(int i = 0;i<numberOfProcess;i++)
{
result = findBestPossiblePartition(processSize[i],partition,numberOfPartition);
resultBlock[i] = result;
}

for(int i = 0;i<numberOfProcess;i++)
cout<<"Process No: "<<i<<"\tAllocated Partition:\t"<<resultBlock[i]<<endl;

39 | P a g e
b) FIRST FIT

i) Fixed Size Allocation


#include<bits/stdc++.h>
using namespace std;
// Code may or may not be correct. Copy at own Risk.

int main(){
int nb,np;
cout<<"Enter Number of Block and Process\n";
cin>>nb>>np;
int block[nb],used[nb],ans[nb];
cout<<"Enter Block sizes:\n";
for(int i=0;i<nb;i++){
cout<<i+1<<": ";
used[i] = 0;
ans[i] = -1;
cin>>block[i];
}
cout<<"Enter Process sizes:\n";
int process[np];
for(int i=0;i<np;i++){
cout<<i+1<<": ";
cin>>process[i];
}
for(int i=0;i<np;i++){
for(int j=0;j<nb;j++){

if(!used[j] && block[j] >= process[i]){


//cout<<block[j]<<" "<<process[i]<<endl;
ans[j]= i;
used[j] = true;
break;
}
}
}
cout<<"Block Process\n";
for(int i=0;i<nb;i++){
cout<<" "<<i+1<<" ";
if(ans[i] == -1){
cout<<"Empty\n";
}
else cout<<ans[i]+1<<"\n";
}

40 | P a g e
41 | P a g e
ii) Variable Size Allocation

#include<bits/stdc++.h>
using namespace std;

int main(){
cout<<"Enter Number of Block and Process\n";
int nb,np;
cin>>nb>>np;
int bSize[nb];
cout<<"Enter Block sizes:\n";

for(int i=0;i<nb;i++){
cout<<i+1<<": ";
cin>>bSize[i];
}
cout<<"Enter Process sizes:\n";
int pSize[np],ans[np];
for(int i=0;i<np;i++){
cout<<i+1<<": ";
cin>>pSize[i];
ans[i] = -1;
}

for(int i=0;i<np;i++){
for(int j=0;j<nb;j++){
if(bSize[j]>= pSize[i]){
ans[i] = j;
if(bSize[j] - pSize[i] >= 0){
bSize[j] -= pSize[i];
}
else bSize[j] = 0;
break;
}
}
}
cout<<"Process Block\n";
for(int i=0;i<np;i++){
cout<<" "<<i+1<<" ";
if(ans[i] == -1){
cout<<"Not Allocated\n";
}
else cout<<ans[i]+1<<"\n";
}

42 | P a g e
43 | P a g e
c) WORST FIT

i) Fixed Size Allocation


#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout << "Enter the number of partitions: ";
cin >> n;
int partition[n], used[n] = {0};
cout << "Enter size of each partition\n";
for(int i = 0; i < n; i++) {
cout << "partition " << i+1 << " : ";
cin >> partition[i];
}
int p;
cout << "Enter number of processes: ";
cin >> p;
int process[p];
int location[p] = {-1};
for(int i = 0; i < p; i++) {
cout << "Process " << i+1 << " : ";
cin >> process[i];
}
for(int i = 0; i < p; i++) {
int mx = 0, pos = -1;
for(int j = 0; j < n; j++) {
int space = partition[j] - process[i];
if(space >= mx && space >= 0 && used[j] == 0) {
mx = space;
pos = j;
}
}
if(pos != -1) {
location[i] = pos+1;
used[pos] = 1;
// partition[pos] -= process[i];
}
else {
location[i] = -1;
}
}
cout << "The proceses are allocated these locations : \n";
for(int i = 0; i < p; i++) {
cout << "Process " << i+1 << " = " << location[i] << endl;
}
return 0;
}

44 | P a g e
45 | P a g e
ii) Variable Size Allocation

#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout << "Enter the number of partitions: ";
cin >> n;
int partition[n];
cout << "Enter size of each partition\n";
for(int i = 0; i < n; i++) {
cout << "partition " << i+1 << " : ";
cin >> partition[i];
}
int p;
cout << "Enter number of processes: ";
cin >> p;
int process[p];
int location[p] = {-1};
for(int i = 0; i < p; i++) {
cout << "Process " << i+1 << " : ";
cin >> process[i];
}
for(int i = 0; i < p; i++) {
int mx = 0, pos = -1;
for(int j = 0; j < n; j++) {
int space = partition[j] - process[i];
if(space >= mx && space >= 0) {
mx = space;
pos = j;
}
}
if(pos != -1) {
location[i] = pos+1;
partition[pos] -= process[i];
}
else {
location[i] = -1;
}
}
cout << "The proceses are allocated these locations : \n";
for(int i = 0; i < p; i++) {
cout << "Process " << i+1 << " = " << location[i] << endl;
}
return 0;
}

46 | P a g e
47 | P a g e
EXPERIMENT 5: EXTERNAL AND INTERNAL FRAGMENTATION
I) Calculation of external and internal fragmentation
#include<stdio.h>
typedef struct{
int t;
int mem;
}block;
int main()
{
int i,j,b[10],n,p,min,s,temp;
block a[10];
printf("enter no of blocks");
scanf("%d",&n);
printf("enter size of blocks ");
for(i=0;i<n;i++)
{
a[i].t=0;
scanf("%d",&a[i].mem);
}
printf("enter no of processes ");
scanf("%d",&p);
for(i=0;i<p;i++)
{
printf("memory required by process %d ",i+1);
scanf("%d",&b[i]);
}
for(i=0;i<p;i++)
{
s=-1;
min=1000;
for(j=0;j<n;j++)
{
temp=a[j].mem-b[i];
if(temp>=0 && temp<min && a[j].t==0)
{
min=temp;
s=j;
}
}
if(s!=-1)
{
a[s].mem=a[s].mem-b[i];
a[s].t=1;
printf("\nprocess %d allocated to block %d ",i+1,s+1);

48 | P a g e
}
else
{
printf("\nnot enough space to allocate process p%d ",i+1);
}
}
printf("\n");
for(i=0;i<n;i++)
printf("block b%d -> status %d memory remaining %d\n",i+1,a[i].t,a[i].mem);
int sum_e=0;
for(i=0;i<n;i++)
{
if(a[i].t==0)
sum_e+=a[i].mem;
}
int sum_i=0;
for(i=0;i<n;i++)
{
if(a[i].t==1)
sum_i+=a[i].mem;
}
printf("\ntotal internal fragmentation is = %d",sum_i);
printf("\ntotal external fragmentation is = %d",sum_e);
return 0;
}

49 | P a g e
EXPERIMENT 6
I) Implementation of Compaction for the continually changing memory layout and
calculate total movement of data.

#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int status;
int mem;
struct node * next;
}node;
inline node * getnode()
{
return (node *)malloc(sizeof(node));
}
void display(node *);
int main()
{
int i;
node *start,*curr,*prev;
printf("initial memory map --BEFORE COMPACTION\n");
int a[7]={1,0,1,1,0,1,0};
int b[7]={320,180,200,230,320,100,40};
for(i=0;i<7;i++)
{
if(i==0)
{
start=getnode();
curr=start;
}
if(i>0)
{
curr->next=getnode();
curr=curr->next;
}
curr->status=a[i];
curr->mem=b[i];
curr->next=NULL;
}
display(start);
curr=start;
prev=start;
int free=0;
while(curr!=NULL)
{
if(curr->status==0)
{
free=free+curr->mem;

50 | P a g e
prev->next=curr->next;
}
else
{
prev=curr;
}
curr=curr->next;
}
prev->next=getnode();
prev=prev->next;
prev->status=0;
prev->mem=free;
prev->next=NULL;
printf("\n");
printf("-----------AFTER COMPACTION\n");
display(start);
}
void display(node *start)
{
node *curr;
curr=start;
printf("BLOCK SIZE ");
while(curr!=NULL)
{
printf("%d ",curr->mem);
curr=curr->next;
}
printf("\n");
printf("STATUS ");
curr=start;
while(curr!=NULL)
{
printf("%d ",curr->status);
curr=curr->next;
}
}

51 | P a g e
EXPERIMENT 7: RESOURCE ALLOCATION GRAPH
I) Implementation of resource allocation graph (RAG).

a) Using Adjacency Matrix


#include<stdio.h>
int main()
{
int p,r,n,i,j,d,e,a[20][20];
printf("enter no of processes\n");
scanf("%d",&p);
printf("enter no of resources\n");
scanf("%d",&r);
n=p+r;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j]=0;
for(i=0;i<p;i++){
printf("enter resourse allocated to process %d\t",i);
scanf("%d",&d);
a[p-1+d][i]=1;
printf("enter resourse requested by process %d\t",i);
scanf("%d",&e);
a[i][p-1+e]=1;}
printf("Adjacency Matrix for Resource allocation Graph---\n");
for(i=0;i<n;i++){
for(j=0;j<n;j++)
printf("%d ",a[i][j]);
printf("\n");}
return 0;}

52 | P a g e
b) Using Adjacency List
#include<stdio.h>
#include<stdlib.h>
struct list
{
int req;
int ass;
struct list *next;
};
struct list * getnode()
{
return (struct list *)malloc(sizeof(struct list)) ;
}
int main()
{
int p,r,i,j,d,e;
printf("enter no of processes\n");
scanf("%d",&p);
printf("enter no of resources\n");
scanf("%d",&r);
struct list *lp[p],*l[p];
for(i=0;i<p;i++)
{
printf("enter resourse allocated to process %d\t",i+1);
scanf("%d",&d);
printf("enter resourse requested by process %d\t",i+1);
scanf("%d",&e);
lp[i]=getnode();
l[i]=lp[i];
for(j=0;j<r;j++)
{
l[i]->ass=0;
l[i]->req=0;
if(j==d-1)
l[i]->ass=1;
if(j==e-1)
l[i]->req=1;
if(j<r-1)
{
l[i]->next=getnode();
l[i]=l[i]->next;
l[i]->next=NULL;
}
}
}
for(i=0;i<p;i++)
{
printf("for p%d -- ",i+1);
while(lp[i]!=NULL)
{

53 | P a g e
printf(" > %d %d",lp[i]->ass,lp[i]->req);
lp[i]=lp[i]->next;
}
printf("\n");
}
}

54 | P a g e
EXPERIMENT 8: BANKER’S ALGORITHM
I) Implementation of Banker’s Algorithm.
#include<bits/stdc++.h>
using namespace std;

void scan_2d(int arr[][100],int row,int col)


{
cout<<"P.No\tResources"<<endl;
cout<<"\t";
for(int i = 0;i<col;i++)
cout<<(char)(i+65)<<" ";

cout<<endl;
for(int i = 0;i<row;i++)
{
cout<<"P"<<i<<"\t";
for(int j = 0;j<col;j++)
{
cin>>arr[i][j];
}
}
}

void scan_1d(int arr[],int col)


{
for(int i = 0;i<col;i++)
cout<<(char)(i+65)<<" ";
cout<<endl;
for(int i = 0;i<col;i++)
cin>>arr[i];
}

void calculateNeed(int allocated[][100],int max[][100],int need[][100],int row,int col)


{
for(int i = 0;i<row;i++)
{
for(int j = 0;j<col;j++)
{
int _need = max[i][j] - allocated[i][j];
if(_need<0)
{
cout<<"wrong data input: more allocated resources to process "<<i<<" of type
"<<(char)(j+65)<<endl;
exit(0);
}
need[i][j] = _need;
}
}
}

55 | P a g e
//return true if arr1>=arr2 for all 1
bool compare(int arr1[],int arr2[],int size)
{
for(int i = 0;i<size;i++)
if(arr1[i]<arr2[i]) return false;
return true;
}

void add(int arr1[],int arr2[],int size)


{
for(int i = 0;i<size;i++)
arr1[i] = arr1[i]+arr2[i];
}

string getSafeStateSequence(int allocated[][100],int available[],int need[][100],bool finish[],int row,int col)


{
string result = "START";
int work[col];

for(int i = 0;i<col;i++)
work[i] = available[i];

for(int i = 0;i<row;i++)
{
if(finish[i]==false&&compare(work,need[i],col))
{
finish[i]=true;
add(work,allocated[i],col);
//cout<<"P"<<(char)(i+48)<<" ";
result+="-->";
result+="P";
result+=(char)(i+48);

i = -1;
}
}

int flag = 0;

for(int i = 0;i<row;i++)
if(!finish[i]) flag=1;

string fail = "NOT POSSIBLE!!! DEADLOCK SITUATION";


if(flag==1)
return fail;
result+="-->END";
return result;
}

56 | P a g e
int main()
{
int m;
int n;
cout<<"enter number of process:\t";
cin>>n;
cout<<"enter number of resources:\t";
cin>>m;
int available[m] = {0};
int allocated[n][100];
int max[n][100];
int need[n][100];
bool finish[n] = {false};
cout<<"enter the Current Allocated Resources:"<<endl;
scan_2d(allocated,n,m);
cout<<"enter the Maximum Required Resources:"<<endl;
scan_2d(max,n,m);
cout<<"enter the current available Resources:"<<endl;
scan_1d(available,m);
calculateNeed(allocated,max,need,n,m);
string sequence = "";
sequence = getSafeStateSequence(allocated,available,need,finish,n,m);
cout<<sequence<<endl;
}

57 | P a g e
EXPERIMENT 9: WAIT FOR GRAPH
I) Identifying circular chain of dependency (i.e., appearance of loops in the graph)
#include<bits/stdc++.h>
using namespace std;
vector<int> graph[100];
int visited[100];
int flag = 0;

void detect_cycle(int cur)


{
visited[cur] = 1;
for(int i = 0;i<graph[cur].size();i++)
{
if(visited[graph[cur][i]]==0)
detect_cycle(graph[cur][i]);
else if(visited[graph[cur][i]]==1)
flag = 1;
}
visited[cur] = 2;
}
int main()
{
int v,e;
cout<<"enter number of resources in wait-for-graph:\t";
cin>>v;
cout<<"enter number of edges in wait-for-graph:\t";
cin>>e;

cout<<"enter resources required by processes:"<<endl;


cout<<"PNo\tRNo"<<endl;
for(int i = 0;i<v;i++)
{
int a,b;
cin>>a>>b;
graph[a].push_back(b);
}
for(int i = 1;i<=v;i++)
{
if(!visited[i])
detect_cycle(i);
}
if(flag)
cout<<"DEADLOCK SITUATION";
else
cout<<"NO DEADLOCK SITUATION";
}

58 | P a g e
59 | P a g e
EXPERIMENT 10: FORK and JOIN construct
I) Program where parent process counts number of vowels in the given sentence and
child process will count number of words in the same sentence. Using FORK and JOIN
construct.

#include<bits/stdc++.h>
#include<sys/types.h>
#include<unistd.h>
using namespace std;

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void inc_bubblesort(int arr[], int n)


{
int i, j;
for (i = 0; i < n-1; i++)

for (j = 0; j < n-i-1; j++)


if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}

void dec_bubblesort(int arr[], int n)


{
int i, j;
for (i = 0; i < n-1; i++)

for (j = 0; j < n-i-1; j++)


if (arr[j] < arr[j+1])
swap(&arr[j], &arr[j+1]);
}

int main()
{
cout<<"Number of Numbers\n";
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int j=fork();
if(j==0)

60 | P a g e
{
cout<<"Child\n";
cout<<"Order is:\n";
dec_bubblesort(arr,n);
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
else
{
cout<<"Parent\n";
cout<<"Order is:\n";
inc_bubblesort(arr,n);
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
}

61 | P a g e
II) Program where parent process sorts array elements in descending order and child
process sorts array elements in ascending order. Use FORK and JOIN construct.
#include<sys/types.h>
#include<bits/stdc++.h>
#include<unistd.h>
using namespace std;

int main()
{
string s;
getline(cin,s);
int j=fork();
int cv=0;
int cw=0;
if(j==0)
{
cout<<"Child\n";
for(int i=0;i<s.length();i++)
if(s[i]=='a'||s[i]=='A'||s[i]=='e'||s[i]=='E'||s[i]=='i'||s[i]=='I'||s[i]=='o'||s[i]=='O'||s[i]=='u'||s[i]=='U')
cv++;
cout<<"Total vowels "<<cv<<endl;
}
else
{
cout<<"Parent\n";
for(int i=0;i<s.length();i++)
if(s[i]==' ')
cw++;
cw++;
cout<<"Total words "<<cw<<endl;
}
}

62 | P a g e
EXPERIMENT 11: IPC - SEMAPHORE
I) Implement the solution for Bounded Buffer (Producer-Consumer) problem using inter
process communication technique – Semaphores.
#include<bits/stdc++.h>
using namespace std;

int mutex=1,full=0,empty=5,item=0;

int wait(int s)
{
return (--s);
}

int signal(int s)
{
return (++s);
}
void producer()
{
empty = wait(empty);
full = signal(full);
mutex = wait(mutex);
item++;
cout<<"Producer produced item "<<item<<endl;
mutex = signal(mutex);
}
void consumer()
{
mutex = wait(mutex);
cout<<"Consumer cxonsumed item "<<item<<endl;
item--;
empty = signal(empty);
full = wait(full);
mutex = signal(mutex);
}
int main()
{
cout<<"Buffer size is 5"<<endl;
cout<<"1.Producer "<<endl<<"2.Consumer "<<endl<<"3.Exit"<<endl<<endl;
while(1)
{
cout<<"Enter your choice : "<<endl;
int ch;
cin>>ch;
switch(ch)
{
case 1 : if(mutex==1 && empty!=0)
{
producer();

63 | P a g e
}
else
{
cout<<"Buffer is full"<<endl;
}
break;
case 2 : if(mutex==1 && full!=0)
{
consumer();
}
else
{
cout<<"Buffer is empty"<<endl;
}
break;
case 3 : return 0;

default : cout<<"Enter valid choice "<<endl;


break;
}
}
}

64 | P a g e
II. Implement the solution for Readers-Writers problem using inter process
communication technique – Semaphores.

import java.util.concurrent.Semaphore;

public class ReaderWriter {

public static final int NUM_OF_READERS = 3;


public static final int NUM_OF_WRITERS = 2;

public static void main(String args[]) {


RWLock database = new Database();

Thread[] readerArray = new Thread[NUM_OF_READERS];


Thread[] writerArray = new Thread[NUM_OF_WRITERS];

for (int i = 0; i < NUM_OF_READERS; i++) {


readerArray[i] = new Thread(new Reader(i, database));
readerArray[i].start();
}

for (int i = 0; i < NUM_OF_WRITERS; i++) {


writerArray[i] = new Thread(new Writer(i, database));
writerArray[i].start();
}
}
}

interface RWLock {
public abstract void acquireReadLock(int readerNum);
public abstract void acquireWriteLock(int writerNum);
public abstract void releaseReadLock(int readerNum);
public abstract void releaseWriteLock(int writerNum);
}

class Database implements RWLock{


private int readerCount;
private Semaphore mutex;
private Semaphore db;

public Database() {
readerCount = 0;
mutex = new Semaphore(1);
db = new Semaphore(1);
}

public void acquireReadLock(int readerNum) {


try {
mutex.acquire();
} catch (InterruptedException e) {}

65 | P a g e
++readerCount;

if (readerCount == 1) {
try {
db.acquire();
} catch (InterruptedException e) {}
}

System.out.println("Reader " + readerNum + " is reading. Reader count = " + readerCount);


mutex.release();
}

public void releaseReadLock(int readerNum) {


try {
mutex.acquire();
} catch (InterruptedException e) {}

--readerCount;

if (readerCount == 0) {
db.release();
}

System.out.println("Reader " + readerNum + " is done reading. Reader count = " + readerCount);
mutex.release();
}

public void acquireWriteLock(int writerNum) {


try {
db.acquire();
} catch (InterruptedException e) {}
System.out.println("Writer " + writerNum + " is writing.");
}

public void releaseWriteLock(int writerNum) {


System.out.println("Writer " + writerNum + " is done writing.");
db.release();
}
}

class Reader implements Runnable


{

private RWLock database;


private int readerNum;

public Reader(int readerNum, RWLock database) {


this.readerNum = readerNum;
this.database = database;
}

66 | P a g e
public void run() {
while (true) {
SleepUtilities.nap();

System.out.println("reader " + readerNum + " wants to read.");

database.acquireReadLock(readerNum);
SleepUtilities.nap();
database.releaseReadLock(readerNum);
}
}
}

class Writer implements Runnable


{
private RWLock database;
private int writerNum;

public Writer(int w, RWLock d) {


writerNum = w;
database = d;
}

public void run() {


while (true){
SleepUtilities.nap();

System.out.println("writer " + writerNum + " wants to write.");

database.acquireWriteLock(writerNum);
SleepUtilities.nap();
database.releaseWriteLock(writerNum);
}
}

}
class SleepUtilities
{
/**
* Nap between zero and NAP_TIME seconds.
*/
public static void nap() {
nap(NAP_TIME);
}

/**
* Nap between zero and duration seconds.
*/
public static void nap(int duration) {

67 | P a g e
int sleeptime = (int) (NAP_TIME);
try { Thread.sleep(sleeptime*1000); }
catch (InterruptedException e) {}
}

private static final int NAP_TIME = 2;


}

68 | P a g e
III) Implement the solution for Dining-Philosopher problem using inter-process
communication technique – Semaphores.

package diningphilosopher;
public class DiningPhilosopher {
public static void main(String[] args)
{
DiningPhilosophersMonitor monitor = new DiningPhilosophersMonitor();
for (int i = 0; i < DiningPhilosophersMonitor.NB_OF_PHILOSOPHERS; i++) {
new Thread(new Philosopher(monitor, i)).start();
}
}
}
class DiningPhilosophersMonitor
{
public static final int NB_OF_PHILOSOPHERS = 5;

private enum State {THINKING, HUNGRY, EATING}


private State[] states = new State[NB_OF_PHILOSOPHERS];
private Object[] self = new Object[NB_OF_PHILOSOPHERS];

public DiningPhilosophersMonitor()
{
for (int i = 0; i < NB_OF_PHILOSOPHERS; i++)
{
this.states[i] = State.THINKING;
System.out.println("Philosopher " + i + " is " + "THINKING");
this.self[i] = new Object();
}
}

public synchronized void takeForks(int i) {


this.states[i] = State.HUNGRY;
System.out.println("Philosopher " + i + " is " + "HUNGRY");

test(i);

if (this.states[i] != State.EATING) {
try {
System.out.println("Philosopher " + i + " is " + "WAITING");
synchronized (this.self[i]) {
this.self[i].wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public synchronized void returnForks(int i) {


this.states[i] = State.THINKING;

69 | P a g e
System.out.println("Philosopher " + i + " is " + "THINKING");

test((i + NB_OF_PHILOSOPHERS - 1) % NB_OF_PHILOSOPHERS);


test((i + 1) % NB_OF_PHILOSOPHERS);
}

private void test(int i) {


if (this.states[(i + NB_OF_PHILOSOPHERS - 1) % NB_OF_PHILOSOPHERS] != State.EATING &&
this.states[i] == State.HUNGRY &&
this.states[(i + 1) % NB_OF_PHILOSOPHERS] != State.EATING)
{
this.states[i] = State.EATING;
System.out.println("Philosopher " + i + " is " + "EATING");

synchronized (this.self[i]) {
this.self[i].notifyAll();
}
}
}
}
class Philosopher implements Runnable
{
private DiningPhilosophersMonitor monitor;
private int i;
public Philosopher(DiningPhilosophersMonitor monitor, int i) {
this.monitor = monitor;
this.i = i;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
monitor.takeForks(i);
SleepUtilities.nap();
monitor.returnForks(i);
}
}
}

class SleepUtilities
{
private static final int NAP_TIME = 5;
public static void nap()
{
nap(NAP_TIME);
}
public static void nap(int duration)
{
int sleeptime = (int) (NAP_TIME * Math.random());
try {
Thread.sleep(sleeptime * 1000);
}

70 | P a g e
catch (InterruptedException e) {}
}
}

71 | P a g e

Das könnte Ihnen auch gefallen