You are on page 1of 68

N.G.

F COLLEGE OF ENGINEERING
AND TECHNOLOGY
PALWAL, HARYANA

OPERATING SYSTEM LAB FILE

CODE: PCC-CS-406

Submitted to: Submitted by:

Mr. MANOJ KUMAR NAME


(Assistant Professor) ROLL NUMBER:-
INDEX
SR. Name of Program Page Signature Remarks
NO. No.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
DOS Internal Commands
These DOS commands are called internal commands because
their code is included in COMMAND.COM, the DOS and Windows
9x command processor. Since COMMAND.COM is loaded into
primary memory when DOS or Windows 9x is booted, the internal
commands are always in memory and can be executed at any time
without first being fetched from disk (secondary memory).This is in
contrast to the disk-bound external commands, which reside only
in secondary memory until the moment they are commanded to
launch. Then they are loaded into primary memory by the
operating system, but only if it can find the program on disk.

The syntax for some frequently used internal commands follows.

General purpose commands

1. CLS:- (Clear the screen) This command is used to clear the screen or
wipe out every thing written on the screen.

Syntax:- C:\> CLS and press Enter

2. DIR:- (Directory) Dir command is used for listing files and directories
present in the current disk.

Syntax:- C:\> DIR [/switches]

Example:- C:\> DIR /P

Switches:-
/P Page wise
/W Widths wise
/S List all files and directory of subdirectories
/AH Display directory with hidden files
/AS Display directory with system files
/AD Display only directories present in current drive

3. VER:-(Version) Version numbers indicates that which edition of DOS we


are working on.

Syntax:- C:\> VER press enter

Output:-
C:\>VER

Windows 98 [Version 4.10.2222]

4. VOL:-(Volume) Displays the disk volume label and serial number, if it


exist.

Syntax:- C:\> VOL press enter


Output:-C:\>VOL
Volume in drive C is JAI
Volume Serial Number is 3E42-1907

5. DATE:- Display the current Date

Syntax:- C:\> DATE


C:\>DATE
Current date is Fri 02-15-2002
Enter new date (mm-dd-yy):

Type DATE without parameters to display the current date setting and
a prompt for a new one. Press ENTER to keep the same date.
Note:- We enter new date in the format of MM-DD-YY.
6. TIME:- Display current time

Syntax:- C:\> TIME


C:\>TIME
Current time is 8:38:47.70a
Enter new time:

Type TIME with no parameters to display the current time setting and a
prompt for a new one. Press ENTER to keep the same time.

Note:- We enter the time in the format of 24 hour clock.

File related commands

7. COPY CON:- This command gives the facility to create a new text file.

Syntax:- C:\> COPY CON <Filename>


C:\>COPY CON Rose.txt
A clock in a office can never get stolen
Too many employees watch it all the time
^Z
1 file(s) copied

After copy con we must specify a suitable file name. Press enter. Start
typing the informations of the file. After gathering the information we press
^Z (CTRL+Z) button or F6 button to save the file. After pressing enter key
computer will show a message like 1 file(s) copied. This means that file is
stored in the disk. Suppose we don't want to save the file or we just want to
abort from file creation job, then we simply press ^C (CTRL+C) button to
abort without saving the file, intend of pressing ^Z button.

Notes:- 1. Never forget to give a suitable filename


2. You can use extension as .TXT for denoting the file as Text file.

8. TYPE:- This command is used to display the contents or text of any file
to the display device.

Syntax:- C:\> TYPE <Filename>


A:\>TYPE GULAB.TXT
A clock in a office can never get stolen
Too many employees watch it all the time

9. COPY :- Copy command is used for copy any file to another location or
to copy the files to another directory. This command may also be used for
copying any file to another disk with different file name.

Syntax:- C:\> COPY <Source filename> <Target file name>


C:\>COPY ROSE.TXT ROSE.MSG
1 file(s) copied

TO copy a file from hard


disk to floppy disk
C:\>COPY Rose.txt A:
1 file(s) copied

To copy a file from Floppy


Disk to Hard disk
A:\>COPY LOTUS.TXT C:\
1 file(s) copied

10. REN:- (Rename) This command is used to change the name of any file
or directory.

Syntax:- C:\> REN <Source filename> <Target filename>


C:\>REN ROSE.TXT GULBAL.TXT
If we get successfully C:\ that means filename or directory name is get
changed. Either it will show the error message.

To changing the filename present in floppy disk


C:\>REN A:\ROSE.TXT GULAB.TXT
Note that you cannot specify a new drive or path for your destination.

11. DEL:- This command is used for erasing any file from the disk.

Syntax:- C:\> DEL <Filename>


C:\>DEL LOTUS.TXT
If it successfully erase the file from dosk then C:\> prompt will be appear,
either computer will show an error message.

Note:- /P option is used for permission before deleting the file.

Directory related commands

12. MD:- (Make Directory)- This command allows to create a new


directory.

Syntax:- C:\> MD <Dirname>


C:\> MD REPORT
C:\>

Now this directory can be used for keeping various sort of reports. Under
this directory we can create another directory which is known as
subdirectory.

13. CD:- (Change Directory):- We can enter or exit from any directory
using this command.

Syntax:- To access any directory


C:\> CD <Directory name>
C:\> CD REPORT
C:\REPORT>

Prompt will change with the directory name. If we keep two dots after CD
command than we will exit from the directory.

Syntax:-C:\> CD..
C:\REPORT> CD..
C:\>

14. RD:-(Remove directory):- This command is used when we want to


remove any unusable directory form our disk.
Syntax:- C:\> RD <Directory name>
C:\> RD REPORT

15. PATH:- This command is used for display or sets directories for
executable files.

Synatx:- C:\> PATH


This command display current path settings.
C:\> PATH=C:\WINDOWS\COMMAND;C:\WINDOWS\;C:\TC
this command will sets the directories windows, the command subfolder of
windows and TC folder for executable files. Operating system will look for
executable files in these directories.

NOTE:- If we need any help for above DOS commands the we put a '/?'
symbol after writting the command at DOS prompt .

Example:- C:\> DIR/? or C:\> COPY/?

External commands:-

There are also Batch commands or Batch files which are text files that
contain a list of internal and/or external commands which are executed
in sequence when the batch file is executed. AUTOEXEC.BAT gets
executed automatically on booting.
In MS-DOS, keyboard shortcuts involving handy ones like Functional
keys, arrows, pipe character (” | “), asterisk (*), ?, [] and ESC are of great
help for recalling to searching to clearing command line etc., Here are
few of them:

▪ UP (↑) and DOWN (↓) arrows recall previously entered commands.


▪ ESC clears the present command line. It abandons the currently
construct command and the next prompt appears.
▪ F1 or → retypes one character at a time from the last command
entry from the current cursor position.
▪ F2 retypes all characters from the last command entry up to the
one identical to your next keystroke. It asks you to enter char to
copy up to and retypes the last command up to that char.
▪ F3 retypes all remaining characters from the last command entry.
▪ F4 stores all characters beginning at the first match with your next
keystroke and ending with the last command entry.
▪ F5 or F8 keys give all the previously typed commands.
▪ F6 places a special end-of-file code at the end of the currently
open file. Sometimes referred to as Ctrl+z or ^z.
▪ F7 key displays command history and ALT+F7/ESC hides it.
▪ F9 is used to select a command by number. Just enter the
command number and it fetches the command line for you.
▪ Pipe character (” | “) combines several series of commands or
programs inter-dependent.
▪ Name enclosed within [] indicate a sub-directory.
▪ Asterisk (*) is used to represent zero or more any characters.
▪ ? is used to present zero or single character.

1. MORE:-Using TYPE command we can see the content of any file. But if
length of file is greater than 25 lines then remaining lines will scroll up. To
overcome through this problem we uses MORE command. Using this
command we can pause the display after each 25 lines.

Syntax:- C:\> TYPE <File name> | MORE


C:\> TYPE ROSE.TXT | MORE
or
C:\> DIR | MORE

2. MEM:-This command displays free and used amount of memory in the


computer.

Syntax:- C:\> MEM


the computer will display the amount of memory.

3. SYS:- This command is used for copy system files to any disk. The disk
having system files are known as Bootable Disk, which are used for booting
the computer.
Syntax:- C:\> SYS [Drive name]
C:\> SYS A:
System files transferred
This command will transfer the three main system files COMMAND.COM,
IO.SYS, MSDOS.SYS to the floppy disk.

4. XCOPY:- When we need to copy a directory instant of a file from one


location to another the we uses xcopy command. This command is much
faster than copy command.

Syntax:- C:\> XCOPY < Source dirname > <Target dirname>


C:\> XCOPY TC TURBOC

5. MOVE:- Move command is used for moving one file or multiple files
from one location to another location or from one disk to another disk.

Syntax:- C:\> MOVE <file name> <path name>


C:\SONGS> MOVE *.MP3 C:\ SONGS\OLD SONGS\

C:\>

6. FC:-(File Compare) This command is capable for comparing two set of


files and display difference between two files.

Syntax:- C:\> FC <First set of file> <Second set of file>


C:\> FC ROSE.TXT GULAB.TXT

7.CHKDSK:-(Check disk) - This command is used to check the status of a


disk and show the report of result status.

Syntax:- C:\> CHKDSK


C:\>CHKDSK

CHKDSK has NOT checked this drive for errors.


You must use SCANDISK to detect and fix errors
on this drive.

Volume JAI created 10-19-2001 7:14p


Volume Serial Number is 3E42-1907

4,203,073,536 bytes total disk space


381,988,864 bytes available on disk

4,096 bytes in each allocation unit


1,026,141 total allocation units on disk
93,259 available allocation units on disk

651,264 total bytes memory


610,784 bytes free

Instead of using CHKDSK, try using SCANDISK.


SCANDISK can reliably detect
and fix a much wider range of disk problems.

8. SORT:- This command is useful when we want to sort a file. When we


run this command the result can be get to display device or file.

Syntax:- C:\> SORT /R < Input file name> <output file name>
Suppose we have a file Player.txt which having the list of a cricket player
team and we want to sort the list of players, then we uses this command
C:\> SORT Player.txt

If we not specify the output file name then result will show to the screen.

/R- switch is used for sorting the file in descending order like from Z to A or
from 9 to 0.
9. FIND:- The FIND command is used to search a file for a text string.

Syntax:- C:\> FIND "String to search" <File name>


C:\TEST>find "office" gulab.txt

---------- gulab.txt
A clock in a office can never get stolen

10. DISKCOPY:- DISKCOPY copies the contents of a floppy disk to


another.

Syntax:- C:\> DISKCOPY <Drive1> <Drive2>


C:\> DISKCOPY A: B:

This command will be copy all contents of A drive to B drive.

11. ATTRIB:- Sets the various type of attribute to a file. Like Read only,
Archive, Hidden and System attribute.

Syntax:- C:\> ATTRIB [± r] [± a] [± h] [± s] <File name>


here r - for read only, a- for archive, h - for hidden, s - for hidden
attribute.
C:\> ATTRIB +r Gulab.txt
This command will change the attribute of file gulab.txt to read only mode.
To remove the read only attribute we will follow this command.
C:\> ATTRIB -r Gulab.txt

12. LABEL:- If you are not happy with the volume label of hard disk, you
can change it.

Syntax:- C:\> LABEL


C:\>LABEL
Volume in drive C is JAI
Volume Serial Number is 3E42-1907
Volume label (11 characters, ENTER for none)? INFOWAY

13. DOSKEY:- Once we install doskey , our dos will star to memorize all
commands we uses. We can recall those commands using up or down arrow
keys. It also gives the facility to create macros, which creates a short key for
long keyword or command.

Key function for Doskey are given as-

UP,DOWN arrows recall commands


Esc clears current command
F7 displays command history
Alt+F7 clears command history
selects a command by
F9
number
Alt+F10 clears macro definitions

Syntax:- C:\> DOSKEY


DOSKey installed

Creating Macros:-
C:\>doskey t=time

C:\>t
C:\>time
Current time is 3:39:05.97p
Enter new time:

To list out all macros defined just type DOSKEY/MACROS at dos prompt
and press enter.
C:\>DOSKEY/MACROS
$D=date
T=time

14. FORMAT:- This command creates new Track & Sectors in a disk.
Every

Syntax:- C:\> FORMAT [drive name] [/S]


C:\> FORMAT A:
this command will create new track & sectors.
C:\> FORMAT A: /S
This command will transfer system files after formatting the disk.
LINUX OPERATING SYSTEM
Linux is a generic term referring to Unix-like computer operating systems based on
the Linux kernel. Their development is one of the most prominent examples of free
and open source software collaboration; typically all the underlying source code can
be used, freely modified, and redistributed, both commercially and non-commercially,
by anyone under licenses such as the GNU General Public License.
Linux can be installed on a wide variety of computer hardware, ranging from
embedded devices such as mobile phones, smartphones and wristwatches to
mainframes and supercomputers. Linux is predominantly known for its use in servers;
in 2007 Linux's overall share of the server market was estimated at 12.7%, while a
2008 estimate suggested that 60% of all web servers ran Linux. Most desktop
computers run either Mac OS X or Microsoft Windows, with Linux having only 1–
2% of the desktop market. However, desktop use of Linux has become increasingly
popular in recent years, partly owing to the popular Ubuntu distribution and the
emergence of netbooks and smartbooks.
Typically Linux is packaged in a format known as a Linux distribution for desktop
and server use. Linux distributions include the Linux kernel and all of the supporting
software required to run a complete system, such as utilities and libraries, the X
Window System, the GNOME and KDE desktop environments, and the Apache
HTTP Server. Commonly-used applications with desktop Linux systems include the
Mozilla Firefox web-browser and the OpenOffice.org office application suite.
The name "Linux" comes from the Linux kernel, originally written in 1991 by Linus
Torvalds. The contribution of a supporting Userland in the form of system tools and
libraries from the GNU Project (announced in 1983 by Richard Stallman) is the basis
for the Free Software Foundation's preferred name GNU/Linux.

Architecture
Linux is a monolithic kernel. Device drivers and kernel extensions run in kernel space
(ring 0 in many CPU architectures), with full access to the hardware, although some
exceptions run in user space. The graphics system most people use with Linux doesn't
run in the kernel, in contrast to that found in Microsoft Windows.
Kernel mode preemption allows device drivers to be preempted under certain
conditions. This feature was added to handle hardware interrupts correctly and
improve support for symmetric multiprocessing (SMP). Preemption also improves
latency, increasing responsiveness and making Linux more suitable for real-time
applications.
Kernel panic
In Linux, a "panic" is an unrecoverable system error detected by the kernel as
opposed to similar errors detected by user space code. It is possible for kernel code to
indicate such a condition by calling the panic function located in the header file
sys/system.h. However, most panics are the result of unhandled processor exceptions
in kernel code, such as references to invalid memory addresses. These are typically
indicative of a bug somewhere in the call chain leading to the panic. They can also
indicate a failure of hardware, such as a failed RAM cell or errors in arithmetic
functions in the processor caused by a processor bug, overheating/damaged processor,
or a soft error.
Programming languages
Linux is written in the version of the C programming language supported by GCC
(which has introduced a number of extensions and changes to standard C), together
with a number of short sections of code written in the assembly language (in GCC's
"AT&T-style" syntax) of the target architecture. Because of the extensions to C it
supports, GCC was for a long time the only compiler capable of correctly building
Linux. In 2004, Intel claimed to have modified the kernel so that its C compiler also
was capable of compiling it. There was another such reported success in 2009 with a
modified 2.6.22.
Many other languages are used in some way, primarily in connection with the kernel
build process (the methods whereby the bootable image is created from the sources).
These include Perl, Python, and various shell scripting languages. Some drivers may
also be written in C++, Fortran, or other languages, but this is strongly discouraged.
Linux's build system only officially supports GCC as a kernel and driver compiler.
Portability
While not originally designed to be portable, Linux is now one of the most widely
ported operating system kernels, running on a diverse range of systems from the iPAQ
(a handheld computer) to the IBM System z9 (a massive mainframe server that can
run hundreds or even thousands of concurrent Linux instances). Linux runs as the
main operating system on IBM's Blue Gene supercomputers. As of June 2009, Linux
is the OS on more than 88% of systems on the Top 500 supercomputers list. Also,
Linux has been ported to various handheld devices such as TuxPhone and Apple's
iPod. The Android operating system, developed for mobile phone devices, uses a
modified version of the Linux kernel.
Virtual machine architectures
The Linux kernel has extensive support for and runs on many virtual machine
architectures both as the host operating system and as a client operating system. The
virtual machines usually emulate Intel x 86 families of processors, though in a few
cases PowerPC or AMD processors are also emulated.
Features of linux
• Multitasking: several programs running at the same time.
• Multiuser: several users on the same machine at the same time (and no two-
user licenses!).
• Multiplatform: runs on many different CPUs, not just Intel.
• Multiprocessor,
• Multithreading: has native kernel support for multiple independent threads of
control within a single process memory space.
• Has memory protection between processes, so that one program can't bring the
whole system down.
• Demand loads executables: Linux only reads from disk those parts of a
program that are actually used.
• Shared copy-on-write pages among executables. This means that multiple
process can use the same memory to run in. When one tries to write to that
memory, that page (4KB piece of memory) is copied somewhere else. Copy-
on-write has two benefits: increasing speed and decreasing memory use.
• Virtual memory using paging (not swapping whole processes) to disk: to a
separate partition or a file in the file system, or both, with the possibility of
adding more swapping areas during runtime (yes, they're still called swapping
areas). A total of 16 of these 128 MB (2GB in recent kernels) swapping areas
can be used at the same time, for a theoretical total of 2 GB of useable swap
space. It is simple to increase this if necessary, by changing a few lines of
source code.
• A unified memory pool for user programs and disk cache, so that all free
memory can be used for caching, and the cache can be reduced when running
large programs.
• Mostly compatible with POSIX, System V, and BSD at the source level.
• All source code is available, including the whole kernel and all drivers, the
development tools and all user programs; also, all of it is freely distributable.
Plenty of commercial programs are being provided for Linux without source,
but everything that has been free, including the entire base operating system, is
still free.
• Supports several common file systems, including minix, Xenix, and all the
common system V file systems, and has an advanced file system of its own,
which offers file systems of up to 4 TB, and names up to 255 characters long.

Advantages

1. Low cost: You don’t need to spend time and money to obtain licenses since
Linux and much of its software come with the GNU General Public License. You
can start to work immediately without worrying that your software may stop
working anytime because the free trial version expires. Additionally, there are
large repositories from which you can freely download high quality software for
almost any task you can think of.
2. Stability: Linux doesn’t need to be rebooted periodically to maintain
performance levels. It doesn’t freeze up or slow down over time due to memory
leaks and such. Continuous up-times of hundreds of days (up to a year or more)
are not uncommon.
3. Performance: Linux provides persistent high performance on workstations and
on networks. It can handle unusually large numbers of users simultaneously, and
can make old computers sufficiently responsive to be useful again.
4. Network friendliness: Linux was developed by a group of programmers over
the Internet and has therefore strong support for network functionality; client and
server systems can be easily set up on any computer running Linux. It can
perform tasks such as network backups faster and more reliably than alternative
systems.
5. Flexibility: Linux can be used for high performance server applications, desktop
applications, and embedded systems. You can save disk space by only installing
the components needed for a particular use. You can restrict the use of specific
computers by installing for example only selected office applications instead of
the whole suite.
6. Compatibility: It runs all common Unix software packages and can process all
common file formats.
7. Choice: The large number of Linux distributions gives you a choice. Each
distribution is developed and supported by a different organization. You can pick
the one you like best; the core functionalities are the same; most software runs on
most distributions.
8. Fast and easy installation: Most Linux distributions come with user-friendly
installation and setup programs. Popular Linux distributions come with tools that
make installation of additional software very user friendly as well.
9. Full use of hard disk: Linux continues work well even when the hard disk is
almost full.
10. Multitasking: Linux is designed to do many things at the same time; e.g., a large
printing job in the background won’t slow down your other work.
11. Security: Linux is one of the most secure operating systems. “Walls” and
flexible file access permission systems prevent access by unwanted visitors or
viruses. Linux users have to option to select and safely download software, free
of charge, from online repositories containing thousands of high quality
packages. No purchase transactions requiring credit card numbers or other
sensitive personal information are necessary.
12. Open Source: If you develop software that requires knowledge or modification
of the operating system code, Linux’s source code is at your fingertips. Most
Linux applications are Open Source as well.
Disadvantages
• Because you must learn unix commands, it takes longer to learn about linux.
• Printed instruction manuals and technical support is much harder to find.
• Configuring devices in linux is generally more difficult.
• Linux does not have an abundance of commercial software such as, word-
processing software, internet explorer and games.
• The linux GUI does not provide as much functionality as the linux CLI
(command line interface).

Linux Basic Commands


Before we go on to the list of commands, you need to open the command line first. If
you are still unsure about the command-line interface, check out this CLI tutorial.

Although the steps may differ depending on the distribution that you’re using, you
can usually find the command line in the Utilities section.

Here is a list of basic Linux commands:

1. pwd command
Use the pwd command to find out the path of the current working directory (folder)
you’re in. The command will return an absolute (full) path, which is basically a path
of all the directories that starts with a forward slash (/). An example of an absolute
path is /home/username.

2. cd command
To navigate through the Linux files and directories, use the cd command. It requires
either the full path or the name of the directory, depending on the current working
directory that you’re in.

Let’s say you’re in /home/username/Documents and you want to go to Photos, a


subdirectory of Documents. To do so, simply type the following
command: cd Photos.

Another scenario is if you want to switch to a completely new directory, for


example,/home/username/Movies. In this case, you have to type cd followed by the
directory’s absolute path: cd /home/username/Movies.
There are some shortcuts to help you navigate quickly:
• cd .. (with two dots) to move one directory up
• cd to go straight to the home folder
• cd- (with a hyphen) to move to your previous directory
On a side note, Linux’s shell is case sensitive. So, you have to
type the name’s directory exactly as it is.

3. ls command
The ls command is used to view the contents of a directory. By default, this
command will display the contents of your current working directory.

If you want to see the content of other directories, type ls and then the directory’s
path. For example, enter ls /home/username/Documents to view the content
of Documents.

There are variations you can use with the ls command:

• ls -R will list all the files in the sub-directories as well


• ls -a will show the hidden files
• ls -al will list the files and directories with detailed
information like the permissions, size, owner, etc.
4. cat command
cat (short for concatenate) is one of the most frequently used commands in Linux. It
is used to list the contents of a file on the standard output (sdout). To run this
command, type cat followed by the file’s name and its extension. For instance: cat
file.txt.

Here are other ways to use the cat command:

• cat > filename creates a new file


• cat filename1 filename2>filename3 joins two files (1 and 2)
and stores the output of them in a new file (3)
• to convert a file to upper or lower case use, cat filename | tr
a-z A-Z >output.txt

5. cp command
Use the cp command to copy files from the current directory to a different directory.
For instance, the command cp
scenery.jpg /home/username/Pictures would create a copy
of scenery.jpg (from your current directory) into
the Pictures directory.
6. mv command
The primary use of the mv command is to move files, although it can also be used to
rename files.

The arguments in mv are similar to the cp command. You need to type mv, the file’s
name, and the destination’s directory. For example: mv file.txt
/home/username/Documents.

To rename files, the Linux command is mv oldname.ext newname.ext

7. mkdir command
Use mkdir command to make a new directory — if you type mkdir Music it will
create a directory called Music.

There are extra mkdir commands as well:

To generate a new directory inside another directory, use this Linux basic
command mkdir Music/Newfile

use the p (parents) option to create a directory in between two existing directories.
For example, mkdir -p Music/2020/Newfile will create the new “2020” file.

8. rmdir command
If you need to delete a directory, use the rmdir command. However, rmdir only
allows you to delete empty directories.

9. rm command
The rm command is used to delete directories and the contents within them. If you
only want to delete the directory — as an alternative to rmdir — use rm -r.

Note: Be very careful with this command and double-check which directory you are
in. This will delete everything and there is no undo.

10. touch command


The touch command allows you to create a blank new file through the Linux
command line. As an example, enter
touch /home/username/Documents/Web.html to create an HTML file
entitled Web under the Documents directory.

11. locate command


You can use this command to locate a file, just like the search command in
Windows. What’s more, using the -i argument along with this command will make it
case-insensitive, so you can search for a file even if you don’t remember its exact
name.

To search for a file that contains two or more words, use an asterisk (*). For
example, locate -i school*note command will search for any file that contains the
word “school” and “note”, whether it is uppercase or lowercase.

12. find command


Similar to the locate command, using find also searches for files and directories. The
difference is, you use the find command to locate files within a given directory.

As an example, find /home/ -name notes.txt command will search for a file
called notes.txt within the home directory and its subdirectories.

Other variations when using the find are:


• To find files in the current directory use, find . -name
notes.txt
• To look for directories use, / -type d -name notes. txt

13. grep command


Another basic Linux command that is undoubtedly helpful for everyday use is grep.
It lets you search through all the text in a given file.

To illustrate, grep blue notepad.txt will search for the word blue in the notepad file.
Lines that contain the searched word will be displayed fully.

14. sudo command


Short for “SuperUser Do”, this command enables you to perform tasks that require
administrative or root permissions. However, it is not advisable to use this command
for daily use because it might be easy for an error to occur if you did something
wrong.

15. df command
Use df command to get a report on the system’s disk space usage, shown in
percentage and KBs. If you want to see the report in megabytes, type df -m.
16. du command
If you want to check how much space a file or a directory takes, the du (Disk Usage)
command is the answer. However, the disk usage summary will show disk block
numbers instead of the usual size format. If you want to see it in bytes, kilobytes, and
megabytes, add the -h argument to the command line.

17. head command


The head command is used to view the first lines of any text file. By default, it will
show the first ten lines, but you can change this number to your liking. For example,
if you only want to show the first five lines, type head -n 5 filename.ext.

18. tail command


This one has a similar function to the head command, but instead of showing the first
lines, the tail command will display the last ten lines of a text file. For example, tail -
n filename.ext.

19. diff command


Short for difference, the diff command compares the contents of two files line by
line. After analyzing the files, it will output the lines that do not match. Programmers
often use this command when they need to make program alterations instead of
rewriting the entire source code.

The simplest form of this command is diff file1.ext file2.ext

20. tar command


The tar command is the most used command to archive multiple files into
a tarball — a common Linux file format that is similar to zip format, with
compression being optional.

This command is quite complex with a long list of functions such as adding new files
into an existing archive, listing the content of an archive, extracting the content from
an archive, and many more. Check out some practical examples to know more about
other functions.

21. chmod command


chmod is another Linux command, used to change the read, write, and execute
permissions of files and directories. As this command is rather complicated, you can
read the full tutorial in order to execute it properly.
22. chown command
In Linux, all files are owned by a specific user. The chown command enables you to
change or transfer the ownership of a file to the specified username. For
instance, chown linuxuser2 file.ext will make linuxuser2 as the owner of
the file.ext.

23. jobs command


jobs command will display all current jobs along with their statuses. A job is
basically a process that is started by the shell.

24. kill command


If you have an unresponsive program, you can terminate it manually by using
the kill command. It will send a certain signal to the misbehaving app and instructs
the app to terminate itself.

There is a total of sixty-four signals that you can use, but people usually only use two
signals:

• SIGTERM (15) — requests a program to stop running and


gives it some time to save all of its progress. If you don’t
specify the signal when entering the kill command, this
signal will be used.
• SIGKILL (9) — forces programs to stop immediately.
Unsaved progress will be lost.

Besides knowing the signals, you also need to know the process identification
number (PID) of the program you want to kill. If you don’t know the PID, simply
run the command ps ux.

After knowing what signal you want to use and the PID of the program, enter the
following syntax:

kill [signal option] PID.

25. ping command


Use the ping command to check your connectivity status to a server. For example, by
simply entering ping google.com, the command will check whether you’re able to
connect to Google and also measure the response time.
26. wget command
The Linux command line is super useful — you can even download files from the
internet with the help of the wget command. To do so, simply type wget followed by
the download link.

27. uname command


The uname command, short for Unix Name, will print detailed information about
your Linux system like the machine name, operating system, kernel, and so on.

28. top command


As a terminal equivalent to Task Manager in Windows, the top command will display
a list of running processes and how much CPU each process uses. It’s very useful to
monitor system resource usage, especially knowing which process needs to be
terminated because it consumes too many resources.

29. history command


When you’ve been using Linux for a certain period of time, you’ll quickly notice that
you can run hundreds of commands every day. As such, running history command is
particularly useful if you want to review the commands you’ve entered before.

30. man command


Confused about the function of certain Linux commands? Don’t worry, you can
easily learn how to use them right from Linux’s shell by using the man command.
For instance, entering man tail will show the manual instruction of the tail
command.

31. echo command


This command is used to move some data into a file. For example, if you want to add
the text, “Hello, my name is John” into a file called name.txt, you would type echo
Hello, my name is John >> name.txt

32. zip, unzip command


Use the zip command to compress your files into a zip archive, and use
the unzip command to extract the zipped files from a zip archive.
33. hostname command
If you want to know the name of your host/network simply type hostname. Adding
a -i to the end will display the IP address of your network.

34. useradd, userdel command


Since Linux is a multi-user system, this means more than one person can interact
with the same system at the same time. useradd is used to create a new user,
while passwd is adding a password to that user’s account. To add a new person
named John type, useradd John and then to add his password type, passwd
123456789.
TO STUDY WINDOWS 2000 OPERATING
SYSTEM
Windows 2000 is a line of operating systems produced by Microsoft for use on
business desktops, notebook computers, and servers. Released on 17 February 2000, it
was the successor to Windows NT 4.0, and is the final release of Microsoft Windows
to display the "Windows NT" designation. It was succeeded by Windows XP for
desktop systems in October 2001 and Windows Server 2003 for servers in April 2003.

Four editions of Windows 2000 were released: Professional, Server, Advanced


Server, and Datacenter Server. Additionally, Microsoft sold Windows 2000 Advanced
Server Limited Edition and Windows 2000 Datacenter Server Limited Edition, which
were released in 2001 and run on 64-bit Intel Itanium microprocessors. While each
edition of Windows 2000 was targeted to a different market, they share a core set of
features, including many system utilities such as the Microsoft Management Console
and standard system administration applications. Support for people with disabilities
has been improved over Windows NT 4.0 with a number of new assistive
technologies, and Microsoft increased support for different languages and locale
information. All versions of the operating system support the Windows NT file
system, NTFS 3.0, the Encrypting File System, as well as basic and dynamic disk
storage. The Windows 2000 Server family has additional features, including the
ability to provide Active Directory services (a hierarchical framework of resources),
Distributed File System (a file system that supports sharing of files) and fault-
redundant storage volumes. Windows 2000 can be installed through either a manual
or unattended installation. Unattended installations rely on the use of answer files to
fill in installation information, and can be performed through a bootable CD using
Microsoft Systems Management Server, by the System Preparation Tool.
Microsoft marketed Windows 2000 as the most secure Windows version ever, but it
became the target of a number of high-profile virus attacks such as Code Red and
Nimda. Over ten years after its release, it continues to receive patches for security
vulnerabilities nearly every month and will continue to do so until 13 July 2010.

Features of Windows 2000


1. Setup Manager: Setup Manager provides a graphic interface to the users to
make installation scripts.
2. Faster Multitasking: It allows user to run multiple programs and perform
different tasks such as browsing, listening music, downloading and working
on the files at the same time.
3. Troubleshooters: It assists users to troubleshoot, optimize and configure a lot
of functionalities of Windows 2000 Professional, which results in greater
performance and greater productivity.
4. Personalized Menu: It adapts the start menu to show the applications that you
most work on.
5. Encrypting File System: With EFS each file can be encrypted with the
randomly generated key. The encryption and decryption features provide a
security layer to the files and folders.
6. IP Security Support: IPSEC is a security protocol that protects the data over
the network. In Virtual Private Networks, IPSEC plays an important role in
securely transmitting the data to the remote location through internet.
7. Microsoft Management Console: MMC provides centralized environment
for the management tools and you can access MMC by typing “MMC” at the
run. You can configure a lot of programs and objects through MMC
8. Intellimirror: Intellimirror provides enhanced access to the information and
software. Intellimirror technology is useful for the mobile computer users.
Intellimirror requires Windows 2000 server to run and the offline feature
enables users to work on their important files when the network connections
are unavailable.
9. Group Policy: Group policy feature of the Windows 2000 Professional
operating system enables the System/Network Administrators to define rules
about security, desktop settings, application settings and user rights. Group
policy works with the active directory and it requires Windows 2000 Server.
10. Hibernation: Hibernation is a very useful utility in Windows 2000
Professional and when you re-activate/turn on your computer hibernation
restores your programs without losing your data.
11. Synchronization: Synchronization makes your files and folders updated by
comparing the files and folders on the network server.
12. Offline Viewing: Offline Viewing feature in Windows 2000 Professional
makes entire web pages including graphics for offline view when internet is
not available.
13. Plug and Play: More than 65,000 devices support this functionality and it is
used for installing the new hardware without the minimum configurations and
work at the user end.
14. Auto Correct: Auto Correct feature automatically corrects the URL
conventions such as http, com, and .org errors.
15. Automated Proxy: Automated proxy feature in Windows 2000 Professional
automatically locate the proxy server on the network and connect to the
internet through that proxy server.
16. Internet Connection Sharing: ICS or Internet Connection Sharing connects
your home of office computer to the internet through the Dial-Up or
broadband internet connection such as DSL, Cable Net etc.
17. Net Meeting: With Net Meeting Conferencing software you can have real
time online chat, teleconferencing with the people throughout the world.
TO STUDY THE GENERAL PURPOSE
COMMANDS IN LINUX.

1. Date
Print the current Date and Time. You may specify a display format. Format can consist of
literal text strings (blanks must be quoted) as well as field descriptors, whose values will
appear as described in the following entries. A privileged user can change the system's date
and time.
Display current date in a nonstandard format. For example:
&dollar; date +"%A %j %n %k %p" Tuesday 248 15 PM
The default is %a %b %e %T %Z %Y (e.g., Tue Sep 5 14:59:37 EDT 2005).
• +%a Abbreviated weekday name (e.g. sun).
• +%b Abbreviated month name (e.g. jan).
• +%e Day of month (e.g. 01)
• +%T Time in %H:%M:%S format.
• +%Y Four-digit year (e.g., 2006).
• +%Z Alphabetic time zone abbreviation (e.g., EDT).
• +%m Month of year (01-12).
• +%h Abbreviated month name (e.g. jan).
• +%y Last two digits of year (00-99).
• +%D Date in %m/%d/%y format.
• +%H Hour in 24-hour format (00-23).
• +%M Minutes (00-59).
• +%S Seconds (00-59).

2. cal
cal [options] [[month] year]
Print a 12-month calendar (beginning with January) for the given year, or a one-month
calendar of the given month and year. Month ranges from 1 to 12. Year ranges from 1 to
9999. With no arguments print a calendar for the current month.
• -m Display Monday as the first day of the week.
• -y Display entire year calendar.
• -1 Display current month calendar.
• -3 Display previous, current and next month calendar.

3. echo
echo [options] [string]
Send (echo) the input string to standard output. This is the /bin/echo command. Echo also
exists as a command built into bash.

4. who
who [options] [file]
Show who is logged into the system. With no options, list the names of users currently logged
in, their terminal, the time they have been logged in, and the name of the host from which
they have logged in. An optional system file (default is /etc/utmp) can be supplied to give
additional information.

5. Ps
The ps (i.e., process status) command is used to provide information about the currently
running processes, including their process identification numbers (PIDs).

The basic syntax of ps is


ps [options]
When ps is used without any options, it sends to standard output, which is the display monitor
by default, four items of information for at least two processes currently on the system: the
shell and ps. A shell is a program that provides the traditional, text-only user interface in
Unix-like operating systems for issuing commands and interacting with the system, and it is
bash by default on Linux. ps itself is a process and it dies (i.e., is terminated) as soon as its
output is displayed.
The four items are labeled PID, TTY, TIME and CMD. TIME is the amount of CPU (central
processing unit) time in minutes and seconds that the process has been running. CMD is the
name of the command that launched the process.
TTY (which now stands for terminal type but originally stood for teletype) is the
name of the console or terminal (i.e., combination of monitor and keyboard) that the
user logged into, which can also be found by using the tty command. This information
is generally only useful on a multi-user network.
.

6. pwd (Print working directory)


Use the pwd command to print the working directory (the current directory you are in).
Example
>pwd
/home
>cd/home/rich/www
>pwd
/home/rich/www
>

Line 1 of this example shows the command pwd has been entered
Line 2 displays, or 'prints' the output of the pwd command (ie: the directory you are in -
/home in this case)
Line 3 uses the cd command (change directory) to move to the /home/rich/www directory
Line 4 enters the pwd command again
Line 5 shows we are now in the /home/rich/www directory
Line 6 is the prompt again.

7. tty
tty [options]
Print the filename of the terminal connected to standard input.
Example
$tty
/dev/pts/10
The terminal file name is 10 (a file named 10) resident in the pts directory. This directory in
turn is under the /dev directory.

8. bc
Calculator.
When bc invoked without arguments, the cursor keeps on blinking and nothing seems to
happen. bc belongs to a family of commands (called filters) that expect input from the
keyboard when used without an argument. key in the following arithmetic expression and
then use [ctrl-d] to quit bc.

Examples:
$ bc
12 + 5
17
bc shows the output of the computation in the next line.

We can make multiple calculations in the same line, using the ; as delimeter. The output of
each computation is, however, shown in a separate line:
12 * 12 ; 2^32 ^ indicate “to the power of”
144
4294967296 Maximum memory possible on a 32-bit machine.

bc performs only integer computation and truncates the decimal portion it sees.
9/5
1

To enable floating-point computation, set scale to the number of digits of precision before you
key in the expression:
scale=2
17 / 7
2.42 Not rounded off, result is actually 2.42857……

bc is quite useful in converting numbers from one base to another (not exceeding 16).
To convert binary numbers to decimal set ibase (input base) to 2 before you provide the
number.
ibase=2
11001010
202 Outout in decimal – base 10

The reverse is also possible with obase:


obase=2
14
1110 Binary in 14

9. man
man [options] [section] [title]
Display information from the online reference manuals. man locates and prints the named title
from the designated reference section.
Traditionally, manpages are divided into nine sections, where section 1 consists of user
commands, section 2 contains system calls, and so forth. By default, all sections are
consulted, so the section option serves to bypass the most common entry and find an entry of
the same name in a different section (e.g., man 2 nice).
TO STUDY THE GENERAL PURPOSE
COMMANDS IN UNIX

Unix Command
See the Unix tutorial for a leisurely, self-paced introduction on how to use
the commands listed below. For more documentation on a command,
consult a good book, or use the man pages. For example, for more
information on grep, use the command man grep.

Contents

• cat --- for creating and displaying short files


• chmod --- change permissions
• cd --- change directory
• cp --- for copying files
• date --- display date
• echo --- echo argument
• ftp --- connect to a remote machine to download or upload files
• grep --- search file
• head --- display first part of file
• ls --- see what files you have
• lpr --- standard print command (see also print )
• more --- use to read files
• mkdir --- create directory
• mv --- for moving and renaming files
• ncftp --- especially good for downloading files via anonymous ftp.
• print --- custom print command (see also lpr )
• pwd --- find out what directory you are in
• rm --- remove a file
• rmdir --- remove directory
• rsh --- remote shell
• setenv --- set an environment variable
• sort --- sort file
• tail --- display last part of file
• tar --- create an archive, add or extract files
• telnet --- log in to another machine
• wc --- count characters, words, lines
TO STUDY THE FILE MANIPULATION
COMMANDS IN LINUX.
The file is a container for storing information.

CATEGORIES:-

• Ordinary file
• Directory file
• Device file

ORDINARY FILE:-Also known as regular file.

o Text file:- contains only printable characters.


o Binary file:- Contains both printable and unprintable characters.

DIRECTORY FILE:-
It contains no data but keeps some details of the file and
subdirectories that contains it.

DEVICE FILE:-
All devices and peripherals are represented by files. To read or write
a device, you have to perform these operations on its associated file.

COMMANDS

1. CAT:displaying and reating files.

cat [options] [files]


Read (concatenate) one or more files and print them on standard output.
You can use the > operator to combine several files into a new file, or >> to append files to an
existing file. When appending to an existing file, use Ctrl-D, the end-of-file symbol, to end
the session.
Examples
cat file1.txt :- Display the content of file1.txt.
cat file1.txt file2.txt > file3.txt :- Reads file1.txt and file2.txt and combines those files
to make file3.txt and display the contents of file3.txt .
cat file1.txt>>file2.txt :- Contents of file1.txt are appended at the end of file2.txt

e.g:- $cat>vidushi
Hello
Welcome to NGFCET
[ctrl-z]
$_

2. cp
cp command copies a file. If I want to copy a file named oldfile in a current directory to a file
named newfile in a current directory.
cp oldfile newfile
If I want to copy oldfile to other directory for example /tmp then
cp oldfile /tmp/newfile.

Useful options available with cp are -p and -r . -p options preserves the modification time
and permissions, -r recursively copy a directory and its files, duplicating the tree structure.

3. rm:- Deleting files.


rm filename

To delete all files:


rm*

Options:-

-i:- For making commands more interactive.

4. MV:- Renaming files

➢ It renames a file.
➢ It moves a group of files to a different directory.

$ mv <old file name> <New file name>

5. WC:- Counting lines, words and characters.

$ wc filename

Output in the format:- lines words characters

OPTIONS:-

i. wc –l filename
ii. wc –w filename
iii. wc –c filename
iv. wc –l-c filename

6. CMP:- Comparing two files.

$ cmp file1 file2

To files are compared byte by byte and the location of first mismatch is echoed to the
screen.

7. LS:- Listing of all the files in the current directory.

OPTIONS:-
i) $ls-l: listing file attributes like permissions, size,ownership.

8. chmod:- Changing file permissions

Relative permissions:-

File permissions:-

r- read
w- write
x- execute

$ chmod u_x filename


$ chmod ugo+r filename
Chmod a-x,go+r filename;ls –l filename

ABSOLUTE PERMISSIONS:-

OCTAL PERMISSIONS SIGNIFICANCE


000 0 --- NO PERMISSION
001 1 --X EXECUTABLE
ONLY
010 2 -W- WRITEABLE
011 3 -WX WRITABLE AND
EXECUTABLE
100 4 R-- READABLE
101 5 R-X READABLE AND
EXECUTABLE
110 6 RW- READABLE AND
WRITEABLE
110 7 RWX READABLE,
WRITABLE AND
EXECUTABLE

$ chmod 666 filename;ls –l filename

10. head:- used to display the no of lines of all files. By default it displays 10
lines from starting.

head -3 filename // It displays 3 lines.

11. tail:- By default it displays 10 lines from bottom.

$ tail -3 filename // displays 3 lines from bottom


12. nl:- for numbering
$ nl filename

Output:-
1. hello
2. gud afternoon
3. jmdsfk

13. grep:- Pattern searching

$ grep pattern filename


Only those lines which have pattern will be displayed.

Option:- $grep –i pattern filename (it ignores uppercase and lower case letters)

14. pipeline command:- output of one becomes input of second command.

$ls|wc –l/ filename

15. gzip:- To compress the file.

Syntax:- $gzip filename

e.g. $wc –l filename


3875302 filename
$gzip filename
$ wc –c filename
788096 filename.gz.

Option:- uncompressing a gzipped file-(-d)


To restore the original file, we have two options.

i. gzip –d
ii. gunzip
iii. eg. Gunzip filename.gz
PROGRAM-1
TO STUDY THE DIRECTORY COMMANDS IN
LINUX.

1. mkdir
mkdir command is used to create directories.

2.rmdir
The rmdir(remove directory ) command removes directories. You simply have to do this to
remove the directory pis

rmdir pis directory must be removed


3. passwd
passwd: Change password. It brings up dialogue that allows you to change your password.

4. script(recording your session)


If you are doing some important work and wish to keep a log of all your activities,you should
invoke this command immediately after you log in:

$ script
script started, file is typescript
$-

5. uname
The uname command displays certain features of the operating system running on
your machine. By default, it simply displays the name of the operating system.
Display host name and info of current system
options: -r print OS release level
-a prints basic info |
-s prints the name of the OS (default)
PROGRAM-2

WRITE A SCRIPT TO SEE CURRENT DATE,


TIME, USERNAME AND CURRENT
DIRECTORY.

Script:-

printf "current date and time is"


date
echo " "
printf "the user logged in is"
logname
echo " "
printf "and current directory is"
pwd

Output:-

$ sh prog7
current date and time isThu Apr 1 09:23:12 EDT 2010

the user logged in isdeepika

and current directory is/home/deepika


PROGRAM-3

WRITE A SCRIPT TO FIND A GIVEN PATTERN


IN GIVEN FILE WHERE PATTERN AND
FILENAME ARE GIVEN AS COMMAND LINE
ARGUMENT.

Script:-

pattern=$1
filename=$2
echo "pattern=" $pattern
echo "filename=" $filename
grep "$pattern" $filename

Output:-

$ sh prog8 current prog7


pattern= current
filename= prog7
printf "current date and time is"
printf "and current directory is"
PROGRAM-4

WRITE A SCRIPT TO SEARCH STRING AND


FILE LINK FROM TERMINAL.

Script:-

echo "enter the pattern to be searched"


read pname
echo "enter the file to be used"
read fname
echo "searching for $pname from file $fname"
grep "$pname" $fname

Output:-

$ sh prog9
enter the pattern to be searched
directory
enter the file to be used
prog7
searching for directory from file prog7
printf "and current directory is"

PROGRAM-5

WRITE A SCRIPT TO ACCEPT TWO


FILENAMES AND CHECK IF BOTH EXISTS AND
THEN APPEND ONE FILE TO ANOTHER.

Script:-

echo "the number of arguments given is $#"


if test -f $1
then
if test -f $2
then
cat $1>>$2
echo "file $1 append to file $2"
else
echo "file with name $2 does not exist"
fi
else
echo "file with name $1 does not exist"
fi

Output:-

$ sh prog10 prog7 abc


the number of arguments given is 2
file with name abc does not exist
PROGRAM-6

WRITE A SCRIPT TO FIND THE LARGEST


NUMBER FROM GIVEN THREE NUMBERS.

Script:-

if test $1 -ge $2 -a $1 -ge $3


then
echo "the greatest number is $1"
elif test $2 -ge $1 -a $2 -ge $3
then
echo "the greatest number is $2"
else
echo "the greatest number is $3"
fi

Output:-

$ sh prog11 56 34 74
the greatest number is 74
PROGRAM-7

WRITE A PROGRAM FOR FIRST COME FIRST


SERVE

#include <stdio.h>
// Function to find the waiting time for all processes
int waitingtime(int proc[], int n,
int burst_time[], int wait_time[]) {
// waiting time for first process is 0
wait_time[0] = 0;
// calculating waiting time
for (int i = 1; i < n ; i++ )
wait_time[i] = burst_time[i-1] + wait_time[i-1] ;
return 0;
}
// Function to calculate turn around time
int turnaroundtime( int proc[], int n,
int burst_time[], int wait_time[], int tat[]) {
// calculating turnaround time by adding
// burst_time[i] + wait_time[i]
int i;
for ( i = 0; i < n ; i++)
tat[i] = burst_time[i] + wait_time[i];
return 0;
}
//Function to calculate average time
int avgtime( int proc[], int n, int burst_time[]) {
int wait_time[n], tat[n], total_wt = 0, total_tat = 0;
int i;
//Function to find waiting time of all processes
waitingtime(proc, n, burst_time, wait_time);
//Function to find turn around time for all processes
turnaroundtime(proc, n, burst_time, wait_time, tat);
//Display processes along with all details
printf("Processes Burst Waiting Turn around \n");
// Calculate total waiting time and total turn
// around time
for ( i=0; i<n; i++) {
total_wt = total_wt + wait_time[i];
total_tat = total_tat + tat[i];
printf(" %d\t %d\t\t %d \t%d\n", i+1, burst_time[i], wait_time[i], tat[i]);
}
printf("Average waiting time = %f\n", (float)total_wt / (float)n);
printf("Average turn around time = %f\n", (float)total_tat / (float)n);
return 0;
}
// main function
int main() {
//process id's
int proc[] = { 1, 2, 3};
int n = sizeof proc / sizeof proc[0];
//Burst time of all processes
int burst_time[] = {5, 8, 12};
avgtime(proc, n, burst_time);
return 0;
}

Output
Processes Burst Waiting Turn around
1 5 0 5
2 8 5 13
3 12 13 25
Average Waiting time = 6.000000
Average turn around time = 14.333333
PROGRAM-8

WRITE A PROGRAM FOR SHORTEST JOB


FIRST

#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter number of process:");
scanf("%d",&n);

printf("nEnter Burst Time:n");


for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1;
}

//sorting of burst times


for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
pos=j;
}

temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}

wt[0]=0;

for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}

avg_wt=(float)total/n;
total=0;

printf("nProcesst Burst Time tWaiting TimetTurnaround Time");


for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
total+=tat[i];
printf("np%dtt %dtt %dttt%d",p[i],bt[i],wt[i],tat[i]);
}

avg_tat=(float)total/n;
printf("nnAverage Waiting Time=%f",avg_wt);
printf("nAverage Turnaround Time=%fn",avg_tat);
}
Output:
PROGRAM-9

WRITE A PROGRAM FOR ROUND ROBIN

#include<stdio.h>
#include<conio.h>

void main()
{
// initlialize the variable name
int i, NOP, sum=0,count=0, y, quant, wt=0, tat=0, at[10], bt[10], temp[10];
float avg_wt, avg_tat;
printf(" Total number of process in the system: ");
scanf("%d", &NOP);
y = NOP; // Assign the number of process to variable y

// Use for loop to enter the details of the process like Arrival time and the Burst Ti
me
for(i=0; i<NOP; i++)
{
printf("\n Enter the Arrival and Burst time of the Process[%d]\n", i+1);
printf(" Arrival time is: \t"); // Accept arrival time
scanf("%d", &at[i]);
printf(" \nBurst time is: \t"); // Accept the Burst time
scanf("%d", &bt[i]);
temp[i] = bt[i]; // store the burst time in temp array
}
// Accept the Time qunat
printf("Enter the Time Quantum for the process: \t");
scanf("%d", &quant);
// Display the process No, burst time, Turn Around Time and the waiting time
printf("\n Process No \t\t Burst Time \t\t TAT \t\t Waiting Time ");
for(sum=0, i = 0; y!=0; )
{
if(temp[i] <= quant && temp[i] > 0) // define the conditions
{
sum = sum + temp[i];
temp[i] = 0;
count=1;
}
else if(temp[i] > 0)
{
temp[i] = temp[i] - quant;
sum = sum + quant;
}
if(temp[i]==0 && count==1)
{
y--; //decrement the process no.
printf("\nProcess No[%d] \t\t %d\t\t\t\t %d\t\t\t %d", i+1, bt[i], sum-
at[i], sum-at[i]-bt[i]);
wt = wt+sum-at[i]-bt[i];
tat = tat+sum-at[i];
count =0;
}
if(i==NOP-1)
{
i=0;
}
else if(at[i+1]<=sum)
{
i++;
}
else
{
i=0;
}
}
// represents the average waiting time and Turn Around time
avg_wt = wt * 1.0/NOP;
avg_tat = tat * 1.0/NOP;
printf("\n Average Turn Around Time: \t%f", avg_wt);
printf("\n Average Waiting Time: \t%f", avg_tat);
getch();
}
Output:
PROGRAM-10

WRITE A PROGRAM FOR PRIORITY


SCHEDULING

#include<stdio.h>
struct process
{
int WT,AT,BT,TAT,PT;
};

struct process a[10];

int main()
{
int n,temp[10],t,count=0,short_p;
float total_WT=0,total_TAT=0,Avg_WT,Avg_TAT;
printf("Enter the number of the process\n");
scanf("%d",&n);
printf("Enter the arrival time , burst time and priority of the process\n");
printf("AT BT PT\n");
for(int i=0;i<n;i++)
{
scanf("%d%d%d",&a[i].AT,&a[i].BT,&a[i].PT);

// copying the burst time in


// a temp array fot futher use
temp[i]=a[i].BT;
}

// we initialize the burst time


// of a process with maximum
a[9].PT=10000;

for(t=0;count!=n;t++)
{
short_p=9;
for(int i=0;i<n;i++)
{
if(a[short_p].PT>a[i].PT && a[i].AT<=t && a[i].BT>0)
{
short_p=i;
}
}

a[short_p].BT=a[short_p].BT-1;
// if any process is completed
if(a[short_p].BT==0)
{
// one process is completed
// so count increases by 1
count++;
a[short_p].WT=t+1-a[short_p].AT-temp[short_p];
a[short_p].TAT=t+1-a[short_p].AT;

// total calculation
total_WT=total_WT+a[short_p].WT;
total_TAT=total_TAT+a[short_p].TAT;

}
}

Avg_WT=total_WT/n;
Avg_TAT=total_TAT/n;

// printing of the answer


printf("ID WT TAT\n");
for(int i=0;i<n;i++)
{
printf("%d %d\t%d\n",i+1,a[i].WT,a[i].TAT);
}

printf("Avg waiting time of the process is %f\n",Avg_WT);


printf("Avg turn around time of the process is %f\n",Avg_TAT);

return 0;
}
Output:-
Enter the number of the process
3
Enter the arrival time , burst time and priority of the process
AT BT PT
033
151
222
ID WT TAT
1 7 10
205
346
Avg waiting time of the process is 3.666667
Avg turn around time of the process is 7.000000
PROGRAM-11

WRITE A PROGRAM FOR MULTIPLE QUEUE


SCHEDULING

#include<stdio.h>
int main()
{
int p[20],bt[20], su[20], wt[20],tat[20],i, k, n, temp;
float wtavg, tatavg;
printf("Enter the number of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i] = i;
printf("Enter the Burst Time of Process%d:", i);
scanf("%d",&bt[i]);
printf("System/User Process (0/1) ? ");
scanf("%d", &su[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(su[i] > su[k])
{
temp=p[i];
p[i]=p[k];
p[k]=temp;
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=su[i];
su[i]=su[k];
su[k]=temp;
}
wtavg = wt[0] = 0;
tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\nPROCESS\t\t SYSTEM/USER PROCESS \tBURST
TIME\tWAITING TIME\tTURNAROUND TIME");
for(i=0;i<n;i++)
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],su[i],bt[i],wt[i],tat[i]);
printf("\nAverage Waiting Time is --- %f",wtavg/n);
printf("\nAverage Turnaround Time is --- %f",tatavg/n);
return 0;
}

Output:-
Enter the number of the process
3
Enter the arrival time , burst time and priority of the process
AT BT PT
033
151
222
ID WT TAT
1 7 10
205
346
Avg waiting time of the process is 3.666667
Avg turn around time of the process is 7.000000
PROGRAM-12

WRITE A PROGRAM FOR SEMAPHORE


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main()
{
int pid;
pid = fork();
srand(pid);
if(pid < 0)
{
perror("fork"); exit(1);
}
else if(pid)
{
char *s = "abcdefgh";
int l = strlen(s);
for(int i = 0; i < l; ++i)
{
putchar(s[i]);
fflush(stdout);
sleep(rand() % 2);
putchar(s[i]);
fflush(stdout);
sleep(rand() % 2);
}
}
else
{
char *s = "ABCDEFGH";
int l = strlen(s);
for(int i = 0; i < l; ++i)
{
putchar(s[i]);
fflush(stdout);
sleep(rand() % 2);
putchar(s[i]);
fflush(stdout);
sleep(rand() % 2);
}
}
}
Output (1st run):

aAABaBCbCbDDcEEcddeFFGGHHeffgghh

(2nd run):

aabbccAABddBCeeCffgDDghEEhFFGGHH
PROGRAM-13

WRITE A PROGRAM FOR PRODUCER


CONSUMER PROBLEM

#include<stdio.h>
#include<stdlib.h>

int mutex=1,full=0,empty=3,x=0;

int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.Producer\n2.Consumer\n3.Exit");
while(1)
{
printf("\nEnter your choice:");
scanf("%d",&n);
switch(n)
{
case 1: if((mutex==1)&&(empty!=0))
producer();
else
printf("Buffer is full!!");
break;
case 2: if((mutex==1)&&(full!=0))
consumer();
else
printf("Buffer is empty!!");
break;
case 3:
exit(0);
break;
}
}
return 0;
}

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

int signal(int s)
{
return(++s);
}

void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\nProducer produces the item %d",x);
mutex=signal(mutex);
}

void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
}
Output
1.Producer
2.Consumer
3.Exit
Enter your choice:1

Producer produces the item 1


Enter your choice:2

Consumer consumes item 1


Enter your choice:2
Buffer is empty!!
Enter your choice:1

Producer produces the item 1


Enter your choice:1

Producer produces the item 2


Enter your choice:1

Producer produces the item 3


Enter your choice:1
Buffer is full!!
Enter your choice:3
PROGRAM-14

WRITE A PROGRAM FOR READER WRITER


PROBLEM

#include<semaphore.h>
#include<stdio.h>
#include<stdlib.h>
sem_t x,y;
pthread_t tid;
pthread_t writerthreads[100],readerthreads[100];
int readercount;

void *reader(void* param)


{
sem_wait(&x);
readercount++;
if(readercount==1)
sem_wait(&y);
sem_post(&x);
printf("\n%d reader is inside",readercount);
sem_wait(&x);
readercount--;
if(readercount==0)
{
sem_post(&y);
}
sem_post(&x);
printf("\n%d Reader is leaving",readercount+1);
}

void *writer(void* param)


{
printf("\nWriter is trying to enter");
sem_wait(&y);
printf("\nWriter has entered");
sem_post(&y);
printf("\nWriter is leaving");
}

int main()
{
int n2,i;
printf("Enter the number of readers:");
scanf("%d",&n2);
int n1[n2];
sem_init(&x,0,1);
sem_init(&y,0,1);
for(i=0;i<n2;i++)
{
pthread_create(&writerthreads[i],NULL,reader,NULL);
pthread_create(&readerthreads[i],NULL,writer,NULL);
}
for(i=0;i<n2;i++)
{
pthread_join(writerthreads[i],NULL);
pthread_join(readerthreads[i],NULL);
}

}
Output
reader is inside
reader is leaving
reader is inside
reader is leaving
writer is trying to enter
writer has entered
writer is leaving
PROGRAM-15

WRITE A PROGRAM FOR SLEEPING BARBER


PROBLEM

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>

// The maximum number of customer threads.


#define MAX_CUSTOMERS 25

// Function prototypes…
void *customer(void *num);
void *barber(void *);

void randwait(int secs);

// Define the semaphores.

// waitingRoom Limits the # of customers allowed


// to enter the waiting room at one time.
sem_t waitingRoom;

// barberChair ensures mutually exclusive access to


// the barber chair.
sem_t barberChair;

// barberPillow is used to allow the barber to sleep


// until a customer arrives.
sem_t barberPillow;

// seatBelt is used to make the customer to wait until


// the barber is done cutting his/her hair.
sem_t seatBelt;

// Flag to stop the barber thread when all customers


// have been serviced.
int allDone = 0;
int main(int argc, char *argv[]) {
pthread_t btid;
pthread_t tid[MAX_CUSTOMERS];
long RandSeed;
int i, numCustomers, numChairs;
int Number[MAX_CUSTOMERS];

printf(“Enter the number of Custmors : “); scanf(“%d”,&numCustomers) ;


printf(“Enter the number of Charis : “); scanf(“%d”,&numChairs);

// Make sure the number of threads is less than the number of


// customers we can support.
if (numCustomers > MAX_CUSTOMERS) {
printf(“The maximum number of Customers is %d.\n”, MAX_CUSTOMERS);
exit(-1);
}

// Initialize the numbers array.


for (i=0; i<MAX_CUSTOMERS; i++) {
Number[i] = i;
}

// Initialize the semaphores with initial values…


sem_init(&waitingRoom, 0, numChairs);
sem_init(&barberChair, 0, 1);
sem_init(&barberPillow, 0, 0);
sem_init(&seatBelt, 0, 0);

// Create the barber.


pthread_create(&btid, NULL, barber, NULL);

// Create the customers.


for (i=0; i<numCustomers; i++) {
pthread_create(&tid[i], NULL, customer, (void *)&Number[i]);
sleep(1);
}

// Join each of the threads to wait for them to finish.


for (i=0; i<numCustomers; i++) {
pthread_join(tid[i],NULL);
sleep(1);
}

// When all of the customers are finished, kill the


// barber thread.
allDone = 1;
sem_post(&barberPillow); // Wake the barber so he will exit.
pthread_join(btid,NULL);
}

void *customer(void *number) {


int num = *(int *)number;

// Leave for the shop and take some random amount of


// time to arrive.
printf(“Customer %d leaving for barber shop.\n”, num);
randwait(2);
printf(“Customer %d arrived at barber shop.\n”, num);

// Wait for space to open up in the waiting room…


sem_wait(&waitingRoom);
printf(“Customer %d entering waiting room.\n”, num);

// Wait for the barber chair to become free.


sem_wait(&barberChair);

// The chair is free so give up your spot in the


// waiting room.
sem_post(&waitingRoom);

// Wake up the barber…


printf(“Customer %d waking the barber.\n”, num);
sem_post(&barberPillow);

// Wait for the barber to finish cutting your hair.


sem_wait(&seatBelt);

// Give up the chair.


sem_post(&barberChair);
printf(“Customer %d leaving barber shop.\n”, num);
}

void *barber(void *junk) {


// While there are still customers to be serviced…
// Our barber is omnicient and can tell if there are
// customers still on the way to his shop.
while (!allDone) {

// Sleep until someone arrives and wakes you..


printf(“The barber is sleeping\n”);
sem_wait(&barberPillow);

// Skip this stuff at the end…


if (!allDone) {
// Take a random amount of time to cut the
// customer’s hair.
printf(“The barber is cutting hair\n”);
randwait(2);
printf(“The barber has finished cutting hair.\n”);

// Release the customer when done cutting…


sem_post(&seatBelt);
}
else {
printf(“The barber is going home for the day.\n”);
}
}
}

void randwait(int secs) {


int len;

// Generate a random number…


len = (int) ((1 * secs) + 1);
sleep(len);
}

You might also like