OS LAB Manual for R23
OS LAB Manual for R23
UNIXOperating System
Lab Manual
II B.TechII Semester
(R19 Regulation)
Command man
Syntax $ man [command] [specific file]
Description “man” stands for manual which is a reference book of Linux Operating System.
It is similar to HELP in popular software.
Examples $ man ls
This command displays the all the information about “ls” command including its
syntax, description and usage.
Command who
Syntax $ who - [option]
Option Description
-a Same as -b -d –login -p -r -t -T -u
-b Time of last system boot
-d Print dead processes
-H Print line of column headings
-l Print system login processes
-m Only hostname and user associated with stdin
-p Print active processes spawned by init
-q All login names and number of users logged on
-r Print current runlevel
-t Print last system clock change
-T Add user’s message status as +, – or ?
-u List users logged in
Description “who” command displays who all are logged onto the network.
2) $ who - H
3) $ who - u
4) $ who – b
Command Cat
Syntax $ cat [argument] [specific file]
Description “cat" is short for concatenate. This command is used to create, view and
concatenate files.
Examples 1) $ cat /etc/passwd
2) $ cat /etc/profile
This command displays the "/etc/profile" file on your screen. Notice that some of the
contents of this file may scroll off of your screen.
This command combines the contents of the first three files into the fourth file.
Description "cd" stands for change directory. It is the primary command for moving around
the filesystem from current directory to the specified directory.
Examples 1) $ cd /usr
This command moves you to the "/usr" directory. "/usr" becomes your current
working directory.
2) $ cd /usr/fred
3) $ cd /u*/f*
Moves you to the "/usr/fred" directory - if this is the only directory matching this
wildcard pattern.
4) $ cd
Issuing the "cd" command without any arguments moves you to your home directory.
5) $ cd -
Using the Korn shell, this command moves you back to your previous working
directory. This is very useful when you're in the middle of a project, and keep moving
back-and-forth between two directories.
Command cp
Syntax $ cp [options] file1 file2
$ cp [options] files directory
Options -b backup files that are about to be overwritten or removed
-i interactive mode; if destination exists, you'll be asked whether to overwrite the file
-p preserves the original file's ownership, group, permissions, and timestamp
Description The "cp" command is used to copy files and directories. Note that when using the cp
command, you must always specify both the source and destination of the file(s) to be
copied. The cp command copies both text and binary files.
Examples 1) $ cp .profile .profile.bak
2) $ cp /usr/fred/Chapter1 .
This command copies the file named "Chapter1" in the "/usr/fred" directory to the
current directory. This example assumes that you have write permission in the current
directory.
3) $ cp /usr/fred/Chapter1 /usr/mary
This command copies the "Chapter1" file in "/usr/fred" to the directory named
"/usr/mary". This example assumes that you have write permission in the "/usr/mary"
directory.
4) $ cp file1 file2
Command ps
Syntax $ ps [options]
Description The "ps" command (process statistics) lets you check the status of processes that
are running on your Unix system. It gives a snapshot of the current process’s
attribute.
Examples 1) $ ps
The ps command by itself shows minimal information about the processes you are
running. Without any arguments, this command will not show information about other
processes running on the system.
2) $ ps -f
The -f argument tells ps to supply full information about the processes it displays. In
this example, ps displays full information about the processes you are running.
3) $ ps -e
The -e argument tells the ps command to show every process running on the system.
4) $ ps -ef
The -e and -f arguments are normally combined like this to show full information
about every process running on the system. This is probably the most often-used form
of the ps command.
5) $ ps -ef | more
Because the output normally scrolls off the screen, the output of the ps -ef command is
often piped into the more command. The more command lets you view one screenful
of information at a time.
6) $ ps -fu fred
This command shows full information about the processes currently being run by the
user named fred (the -u option lets you specify a username).
Command ls
Syntax $ ls [options] [names]
Description "ls" stands for list. It is used to list information about files and directories.
Examples 1) $ ls
This is the basic "ls" command, with no options. It provides a very basic listing of the
files in your current working directory. Filenames beginning with a decimal are
considered hidden files, and they are not shown.
2) $ ls -a
The -a option tells the ls command to report information about all files, including
hidden files.
3) $ ls -l
The -l option tells the "ls" command to provide a long listing of information about the
files and directories it reports. The long listing will provide important information
about file permissions, user and group ownership, file size, and creation date.
4) $ ls -al
This command provides a long listing of information about all files in the current
directory. It combines the functionality of the -a and -l options. This is probably the
most used version of the ls command.
5) $ ls -al /usr
This command lists long information about all files in the "/usr" directory.
This command lists long information about all files in the "/usr" directory, and all sub-
directories of /usr. The -r option tells the ls command to provide a recursive listing of
all files and sub-directories.
7) $ ls -ld /usr
Rather than list the files contained in the /usr directory, this command lists information
about the /usr directory itself (without generating a listing of the contents of /usr). This
is very useful when you want to check the permissions of the directory, and not the
files the directory contains.
Command mv
Syntax $ mv [options] sources target
Options -b backup files that are about to be overwritten or removed.
-i interactive mode; if destination file exists, you'll be asked whether to overwrite the
file or not.
Description The "mv" command is used to move and rename files.
Examples 1) $ mv Chapter1 Chapter1.bad
This command renames the file "Chapter1" to the new name "Chapter1.bad".
2) $ mv Chapter1 garbage
This command renames the file "Chapter1" to the new name "garbage". (Notice that if
"garbage" is a directory, "Chapter1" would be moved into that directory).
3) $ mv Chapter1 /tmp
This command moves the file "Chapter1" into the directory named "/tmp".
4) $ mv tmp tmp.old
Assuming in this case that tmp is a directory, this example renames the directory tmp
to the new name tmp.old.
Command rm
Syntax $ rm [options] files
Options -d, --directory
unlink FILE, even if it is a non-empty directory (super-user only)
-f, --force
ignore nonexistent files, never prompt
-i, --interactive
prompt before any removal
-v, --verbose
explain what is being done
Description The "rm" command is used to remove files and directories. (Warning - be very
careful when removing files and directories!)
Examples 1) $ rm Chapter1.bad
This command deletes the file named "Chapter1.bad" (assuming you have permission
to delete this file).
This command deletes the files named "Chapter1", "Chapter2", and "Chapter3".
This command prompts you before deleting any of the three files specified. The -i
option stands for inquire. You must answer y (for yes) for each file you really want to
delete. This can be a safer way to delete files.
4) $ rm *.html
This command deletes all files in the current directory whose filename ends with the
characters ".html".
5) $ rm index*
This command deletes all files in the current directory whose filename begins with the
characters "index".
6) $ rm -r new-novel
This command deletes the directory named "new-novel". This directory, and all of its'
contents, are erased from the disk, including any sub-directories and files.
Command grep
Syntax $ grep [options] regular expression [files]
Options -i case-insensitive search
-n show the line# along with the matched line
-v invert match, e.g. find all lines that do NOT match
-w match entire words, rather than substrings
Description Think of the "grep" command as a "search" command (most people wish it was
named "search"). It is used to search for text strings within one or more files.
Examples 1) $ grep 'fred' /etc/passwd
This command searches for all occurrences of the text string 'fred' within the
"/etc/passwd" file. It will find and print (on the screen) all of the lines in this file that
contain the text string 'fred', including lines that contain usernames like "fred" - and
also "alfred".
This command searches for all occurrences of the text string 'fred' within the
"/etc/passwd" file, but also requires that the "f" in the name "fred" be in the first
column of each record (that's what the caret character tells grep). Using this more-
advanced search, a user named "alfred" would not be matched, because the letter "a"
will be in the first column.
3) $ grep 'joe' *
This command searches for all occurrences of the text string 'joe' within all files of the
current directory.
Command mkdir
Syntax $ mkdir [options] directory name
Description The "mkdir" command is used to create new directories (sub-directories).
Examples 1) $ mkdir tmp
This command creates a new directory named "tmp" in your current directory. (This
example assumes that you have the proper permissions to create a new sub-directory
in your current working directory.)
This command creates three new sub-directories (memos, letters, and e-mail) in the
current directory.
3) $ mkdir /usr/fred/tmp
This command creates a new directory named "tmp" in the directory "/usr/fred". "tmp"
is now a sub-directory of "/usr/fred". (This example assumes that you have the proper
permissions to create a new directory in /usr/fred.)
4) $ mkdir -p /home/joe/customer/acme
Command rmdir
Syntax $ rmdir [options] directories
Description The "rmdir" command is used to remove directories. (Warning - be very careful
when removing files and directories!)
Examples $rmdir customer
This command deletes the directory named "customer" (assuming you have
permission to delete this directory).
Command echo
Syntax $ echo [options] IDs
Description The “echo” command is used to display a line of text, or messages. It takes zero, one r
more arguments.
Examples 1) $ echo hi
Two words can be displayed using echo by placing them in quotes.The output of the
above command will be – Hello World
Command more
Syntax $ more [filename]
Description This command is used to display the contents of a file. It allows us to set the output
page size and pauses at the end of each page to allow us to read the file.
Examples $ more chapter1
Command date
Syntax $ date [- options]
Description The “date” command prints the date and time. Using this command, the user ca
display the current date along with the time nearest to the second.
Examples $ date
Command time
Syntax $ time [options]
Description This command is used to know the resource usage. It runs a program or command
with given arguments, generates a timing statistics about the program run and directs
this statistics report to the standard output.
Examples $ time
Real 0m0.000s
User 0m0.000s
Sys 0m0.000s
Command kill
Syntax $ kill [options] IDs
Description The command “kill” ends one or more process IDs. In order to do this you must own
the process or be designated a privileged user. To find the process ID of a certain job
use “ps” command.
Examples $ kill 456
Command history
Syntax $ history
Description The command “history” is used to display the history of previous executed commands.
When used without options, it displays the command history list with line numbers.
Examples $ history
1 pwd
2 date
3 cal
Command chmod
Syntax $ chmod<permissions><filename>
Description The “chmod” command is used to change permissions of a file after its creation. Only
the Owner or Super User can change file permissions.
Examples $ chmod u+x sample
$ls - l sample
-r w x r --r --sample
Command chown
Syntax $ chown <new_owner><filename>
Description The command “chown” is used to change the file’s owner and group. Only the
owner can change the major attributes of a file. Sometimes it is necessary to
change the ownership of a file.
Examples $ls -l sample
$ls -l sample
Command finger
Syntax $ finger
Description It is a user information lookup command. The “finger” command displays
information about the system users.
Examples $finger
Command pwd
Syntax $ pwd
Description "pwd" stands for print working directory. It displays your current position in the
UNIX filesystem. i.e., the location of the current directory in the directory
sttucture. There are no options (or arguments) with the "pwd" command
Examples $ pwd
Command cal
Syntax $ cal <month><year>
Description This command is used to print the calendar of a specific month or a specific
year.
Examples $ cal 05 2021
Command logout
Syntax $ logout
Description This command is used to logout from the shell.
Examples $ logout
Command shutdown
Syntax $shutdown
Description This command is used to shutting down the system in a safe way.
Examples $ shutdown
b) Study of vi editor.
What is vi?
The fundamental UNIX editor is called vi. Vi stands for visual. It is a primitive editor, but it
will be found on every UNIX system, and works well when logging in remotely from home. There
are just a few commands that one needs to learn at first, and they will be sufficient to write simple
files. The editor allows the users to see a portion of a file on the screen and to modify characters and
lines by simply typing at the cursor positon.
The Basics of vi
There are essentially three Modes in vi, the Insert Mode where one is typing in new text,
the Edit Mode where one is modifying text that is already there, and the Command Mode where
one is interacting with the operating system with actions like reading and writing files.
Most of the commands require just a simple letter or two, but be careful to note that vi is case
sensitive, and capital letters do different things from lower case letters. It is not necessary to learn all
of these commands, but eventually they will become second nature. The basic operations needed to
create a file are related to each of those modes, so let's look at them separately.
Letter Action
EDIT Mode
Modifying Text
r Replaces the character under the cursor with the next thing typed
p Puts the yanked text on the line below the cursor (lower case p)
Note: If vi is already in the input mode, text from that or another window may be
highlighted using the left mouse button, and copied into place by pressing the middle
mouse button.
Letter Action
Syntax:
$vi filename
- To add text at the end of the file, position the cursor at the last character of the file.
- The editor accepts and inserts the typed character until Esc key is pressed.
Saving text:
Quitting vi:
Bourne again shell (Bash) is a free Unix shell that can be used in place of the Bourne shell. It is a
complete implementation of the IEEE Portable Operating System Interface for Unix (POSIX) and
Open Group shell specification.
Bash is basically a command processor that typically runs in a text window, allowing the user to type
commands that cause actions. It can read commands from a file, called a script. Like all Unix shells
it supports the following:
Bash was written for the GNU Project by Brian Fox. It is called Bourne again shell for many
reasons, the first being that it is the open-source version of the Bourne shell and the second as a pun
on the concept of being born again. Its acronym is also a description of what the project did, which
was to bash together sh, csh, and ksh features.
A Unix shell is a command-line interpreter that provides users with a basic user interface. It
allows users to communicate with the system through a series of commands that are typed in the
command-line window. There are no buttons or pop-up windows in a shell, simply lots and lots of
text.
Essentially, Bash allows users of Unix-like systems to control the innermost components of
the operating system using text-based commands.
Bash has a number of extensions and runs on Unix-like operating systems like Linux and
Mac OS X. It was ported to Windows through the Subsystem for UNIX-based Applications (SUA)
and by POSIX emulation using Cygwin or MSYS. It can even be used in MS-DOS.
Study of Bourne shell
A Bourne shell (sh) is a UNIX shell or command processor that is used for scripting. It was
developed in 1977 by Stephen Bourne of AT&T and introduced in UNIX Version 7, replacing the
Mashey shell (sh).
The Bourne shell is also known by its executable program name, "sh" and the dollar symbol,
"$," which is used with command prompts
A Bourne shell interprets and executes user defined commands and provides command based
programming abilities. A Bourne shell enables the writing and executing of shell scripts, which
provide basic program control flow, control over input/output (I/O) file descriptors and all key
features required to create scripts or structured programs for shell.
A Bourne shell also executes commands and functions that are predefined or integrated; files
that search or follow a command path, as well as text file commands.
The Bourne shell's architectural code was implemented in subsequent versions of UNIX
shell, including Bourne Again shell (Bash), Korn shell and Zsh shell.
Study of C shell
The C shell was created by Bill Joy while he was a graduate student at UC Berkeley in the
late 1970s. It was first released as part of the 2BSD Berkeley Software Distribution of Unix in 1978.
The C shell gets its name from its syntax, which is intended to resemble the C programming
language.
The C shell (csh) is a command shell for Unix-like systems that was originally created as part
of the Berkeley Software Distribution (BSD) in 1978. Csh can be used for entering commands
interactively or in shell scripts. The shell introduced a number of improvements over the earlier
Bourne shell designed for interactive use. These include history, editing operations, a directory
stack, job control and tilde completion. Many of these features were adopted in the Bourne Again
shell (bash), Korn shell (ksh) and in the Z shell (zsh). A modern variant, tcsh, is also very popular.
The C shell introduced features that were intended to make it easier to use interactively at the
command line, though like other shells it is capable of being scripted. One of the most notable
features was command history. Users can recall previous commands they have entered and either
repeat them or edit these commands. Aliases allow users to define short names to be expanded into
longer commands. A directory stack lets users push and pop directories on the stack to jump back
and forth quickly. The C shell also introduced the standard tilde notation where "~" represents a
user's home directory.
Most of these features have been incorporated into later shells, include the Bourne Again
shell, the Korn shell and the Z shell. A popular variant is tsch, which is the current default shell on
BSD systems, as well as on early versions of Mac OS X.
d) Study of Unix/Linux file system (tree structure).
Unix file system is a logical method of organizing and storing large amounts of information in a
way that makes it easy to manage. A file is a smallest unit in which the information is stored. Unix
file system has several important features. All data in Unix is organized into files. All files are
organized into directories. These directories are organized into a tree-like structure called the file
system.
Files in Unix System are organized into multi-level hierarchy structure known as a directory tree. At
the very top of the file system is a directory called “root” which is represented by a “/”. All other
files are “descendants” of root.
/ :The slash / character alone denotes the root of the filesystem tree.
/bin :Stands for “binaries” and contains certain fundamental utilities, such as ls or cp, which
are generally needed by all users.
/boot :Contains all the files that are required for successful booting process.
/dev :Stands for “devices”. Contains file representations of peripheral devices and pseudo-
devices.
/etc :Contains system-wide configuration files and system databases. Originally also
contained “dangerous maintenance utilities” such as init,but these have typically been moved
to /sbin or elsewhere.
/home :Contains the home directories for the users.
/lib :Contains system libraries, and some critical files such as kernel modules or device
drivers.
/media :Default mount point for removable devices, such as USB sticks, media players, etc.
/mnt :Stands for “mount”. Contains filesystem mount points. These are used, for example, if
the system uses multiple hard disks or hard disk partitions. It is also often used for remote
(network) filesystems, CD-ROM/DVD drives, and so on.
/proc :procfs virtual filesystem showing information about processes as files.
/root :The home directory for the superuser “root” – that is, the system administrator. This
account’s home directory is usually on the initial filesystem, and hence not in /home (which
may be a mount point for another filesystem) in case specific maintenance needs to be
performed, during which other filesystems are not available. Such a case could occur, for
example, if a hard disk drive suffers physical failures and cannot be properly mounted.
/tmp :A place for temporary files. Many systems clear this directory upon startup; it might
have tmpfs mounted atop it, in which case its contents do not survive a reboot, or it might be
explicitly cleared by a startup script at boot time.
/usr :Originally the directory holding user home directories,its use has changed. It now holds
executables, libraries, and shared resources that are not system critical, like the X Window
System, KDE, Perl, etc. However, on some Unix systems, some user accounts may still have
a home directory that is a direct subdirectory of /usr, such as the default as in Minix. (on
modern systems, these user accounts are often related to server or system use, and not
directly used by a person).
/usr/bin : This directory stores all binary programs distributed with the operating system not
residing in /bin, /sbin or (rarely) /etc.
/usr/include :Stores the development headers used throughout the system. Header files are
mostly used by the #include directive in C/C++ programming language.
/usr/lib :Stores the required libraries and data files for programs stored within /usr or
elsewhere.
/var :A short for “variable.” A place for files that may change often – especially in size, for
example e-mail sent to users on the system, or process-ID lock files.
/var/log :Contains system log files.
/var/mail :The place where all the incoming mails are stored. Users (other than root) can
access their own mail only. Often, this directory is a symbolic link to /var/spool/mail.
/var/spool :Spool directory. Contains print jobs, mail spools and other queued tasks.
/var/tmp :A place for temporary files which should be preserved between system reboots.
e) Study of .bashrc, /etc/bashrc and Environment variables.
A variable is a character string to which we assign a value. The value assigned could be a number,
text, filename, device, or any other type of data.
For example, first we set a variable TEST and then we access its value using the echo command −
$TEST="Unix Programming"
$echo $TEST
Unix Programming
Note that the environment variables are set without using the $ sign but while accessing them we use
the $ sign as prefix. These variables retain their values until we come out of the shell.
When you log in to the system, the shell undergoes a phase called initialization to set up the
environment. This is usually a two-step process that involves the shell reading the following files −
/etc/profile
profile
As soon as both of these files have been read, the shell displays a prompt −
This is the prompt where you can enter commands in order to have them executed.
Note − The shell initialization process detailed here applies to all Bourne type shells, but some
additional files are used by bash and ksh.
The file /etc/profile is maintained by the system administrator of your Unix machine and contains
shell initialization information required by all users on a system.
The file .profile is under your control. You can add as much shell customization information as you
want to this file. The minimum set of information that you need to configure includes −
You can check your .profile available in your home directory. Open it using the vi editor and check
all the variables set for your environment.
Environment Variables
Following is the partial list of important environment variables. These variables are set and accessed
as mentioned below −
4 LANG expands to the default system locale; LC_ALL can be used to override this. For
example, if its value is pt_BR, then the language is set to (Brazilian) Portuguese and the
locale to Brazil.
LD_LIBRARY_PATH
5 A Unix system with a dynamic linker, contains a colonseparated list of directories that the
dynamic linker should search for shared objects when building a process image after exec,
before searching in any other directories.
PATH
6
Indicates the search path for commands. It is a colon-separated list of directories in which the
shell looks for commands.
PWD
7
Indicates the current working directory as set by the cd command.
RANDOM
8
Generates a random integer between 0 and 32,767 each time it is referenced.
SHLVL
9
Increments by one each time an instance of bash is started. This variable is useful for
determining whether the built-in exit command ends the current session.
TERM
10
Refers to the display type.
TZ
11
Refers to Time zone. It can take values like GMT, AST, etc.
UID
12
Expands to the numeric user ID of the current user, initialized at the shell startup.
MAIL
13
This variable holds the absolute pathname of the file where user’s mail is kept. Usually
the name of this file is the user’s login name
SHELL
14
This variable contains the name of the users shell program in the form of absolute
pathname. System administrator sets the default shell If required, user can change it
TERM
15
This variable holds the information regarding the type of the terminal being used. If
TERM is not set properly, utilities like vi editor will not work
$ echo $HOME
/root
]$ echo $DISPLAY
$ echo $TERM
xterm
$ echo $PATH
/usr/local/bin:/bin:/usr/bin:/home/amrood/bin:/usr/local/bin
$
.bashrc
.bashrc file is automatically executed when new terminal(shell) is opened.
Purpose of bashrc file:
You can export environment variables(So there is no need to export environment variable
every time)
You can define aliases
You can provide the path for cross compiler
You can add your own script which can start automatically whenever new shell is opened.
You can change the history length
/etc/bashrc
Like .bash_profile you will also commonly see a .bashrc file in your home directory. This file is
meant for settingcommand aliases and functions used by bash shell users.
Just like the /etc/profile is the system wide version of .bash_profile. The /etc/bashrc for Red
Hat and /etc/bash.bashrc in Ubuntu is the system wide version of .bashrc.
Interestingly enough in the Red Hat implementation the /etc/bashrc also executes the shell
scripts within /etc/profile.d but only if the users shell is a Interactive Shell (aka Login Shell)
2.Write a C program that makes a copy of a file using standard I/O, and system
calls.
DESCRIPTION:-The open() function opens the file associated with file descriptor in the specified
mode.The read() function attempts to read nbytes from the file associated with file descriptor and
places the characters read into buffer. The write() function attempts to write nbytes from buffer to the
file associated with file descriptor.The close() function closes the file associated with the file.
descriptor.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
if (argc != 3) {
printf("Usage: cp file1 file2");
return 1;
}
/* Create input file descriptor */
fd1 = open(argv[1], O_RDONLY);
if (fd1 == -1) {
perror("open");
return 2;
}
/* Create output file descriptor */
fd2 = open(argv[2], O_WRONLY | O_CREAT, 0644);
if (fd2 == -1) {
perror("open");
return 3;
}
/* Copy process */
while ((ret_in = read(fd1, & buffer, BUF_SIZE)) > 0) {
write(fd2, & buffer, (ssize_t) ret_in);
}
close(fd1);
close(fd2);
}OUTPUT:
3. Write a C program to emulate the UNIX ls –l command
Description:The ls command lists the files and folders in the current directory. –l option is used for
long listing format.For each file named, ls lists information for that file.
Program:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
printf(“\nFork failed\n”);
exit (-1); }
ls }
else { //parent
printf(“\nchild complete\n”);
exit (0);
}}
OUTPUT:
Ex:- ls –l | wc
Description: A pipe is a technique for passing information from one program process to another.
Unlike other forms of inter process communication (IPC), a pipe is one-way communication only.
Basically, a pipe passes a parameter such as the output of one process to another process which
accepts it as input. The system temporarily holds the piped information until it is read by the
receiving process.
Program:
#include<stdio.h>
#include<fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
void main() {
int pfd[2], p;
pipe(pfd);
p = fork();
if (p == 0) { //child process
close(pfd[0]);
close(1);
dup(pfd[1]);
execlp("ls", "ls", "-l", NULL);
} else { //parent process
close(pfd[1]);
close(0);
dup(pfd[0]);
execlp("wc", "wc", NULL);
}
}
OUTPUT:
5) Simulate the following CPU scheduling algorithm
a)FCFS Scheduling
Description
Simplest CPU-scheduling algorithm is the first come, first-served (FCFS) scheduling
algorithm. The process that requests the CPU first is allocated the CPU first. The implementation of
the FCFS policy is easily managed with a FIFO queue. When a process enters the ready queue, it is
linked onto the tail of the queue. When the CPU is free, it is allocated to the process at the head of
the queue. The running process is then removed from the queue.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
charpn[10][10];
intarr[10],bur[10],star[10],finish[10],tat[10],wt[10],i,n;
inttotwt=0,tottat=0;
OUTPUT:
Description:-
A different approach to CPU scheduling is the shortest-job first (SJF) scheduling algorithm.
This algorithm associates with each process the length of the next CPU burst. When the CPU is
available, it is assigned to the process that has the smallest next CPU burst. if two processes have the
same length next CPU burst, FCFS scheduling is used to break the tie.
Program
#include<stdio.h>
#include<string.h>
void main()
{
intpn[10],et[20],at[10],n,i,j,temp,st[10],ft[10],wt[10],ta[10];
inttotwt=0,totta=0;
floatawt,ata;
printf("Enter the number of process:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter process number, arrival time & execution time:");
scanf("%d%d%d",&pn[i],&at[i],&et[i]);
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(et[i]<et[j])
{
temp=at[i];
at[i]=at[j];
at[j]=temp;
temp=et[i];
et[i]=et[j];
et[j]=temp;
temp=pn[i];
pn[i]=pn[j];
pn[j]=temp;
}
}
for(i=0;i<n;i++)
{
if(i==0)
{
st[i]=at[i];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
else
{
st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
}
for(i=0;i<n;i++)
{
totwt+=wt[i];
totta+=ta[i];
}
awt=(float)totwt/n;
ata=(float)totta/n;
printf("\nPname\tarrivaltime\texecutiontime\twaitingtime\ttatime");
for(i=0;i<n;i++)
printf("\n%d\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],wt[i],ta[i]);
printf("\nAverage waiting time is:%f",awt);
printf("\nAverageturnaroundtime is:%f",ata);
}
OUTPUT:
Description:
The SJF algorithm is a special case of the general priority-scheduling algorithm. A priority is
associated with each process, and the CPU is allocated to the process with the highest priority.
Equal-priority processes are scheduled in FCFS order. Priorities are generally some fixed range of
numbers such as 0 to 7, 0 to 4095.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int pn[10],et[20],at[10],n,i,j,temp,p[10],st[10],ft[10],wt[10],ta[10];
inttotwt=0,totta=0;
floatawt,ata;
clrscr();
printf("Enter the number of process:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter process number,arrivaltime,execution time & priority:");
flushall();
scanf("%d%d%d%d",&pn[i],&at[i],&et[i],&p[i]);
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(p[i]<p[j])
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
temp=at[i];
at[i]=at[j];
at[j]=temp;
temp=et[i];
et[i]=et[j];
et[j]=temp;
temp=pn[i];
pn[i]=pn[j];
pn[j]=temp;
}
}
for(i=0;i<n;i++)
{
if(i==0)
{
st[i]=at[i];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
else
{
st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
}
totwt+=wt[i];
totta+=ta[i];
}
awt=(float)totwt/n;
ata=(float)totta/n;
printf("\nPno\tarrivaltime\texecutiontime\tpriority\twaitingtime\ttatime");
for(i=0;i<n;i++)
printf("\n%d\t%5d\t\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],p[i],wt[i],ta[i]);
printf("\nAverage waiting time is:%f",awt);
printf("\nAverageturnaroundtime is:%f",ata);
}
OUTPUT:
DESCRIPTION:-
The round-robin scheduling algorithm is designed especially for time-sharing systems. It is
similar to FCFS scheduling, but preemption is added to switch between processes. A small unit of
time called a time quantum is defined. The ready queue is treated as a circular queue. The CPU
scheduler goes around the ready queue, allocating the CPU to each process for a time interval of up
to 1 time quantum.
To implement RR scheduling we keep the ready queue as a FIFO queue of processes. New
processes are added to the tail of the ready queue. The CPU scheduler picks the first process from
the ready queue, sets a timer to interrupt after 1 time quantum and dispatches the process.
#include<stdio.h>
main()
{
int i,j,n,tq,time=0,p[10],st[10],b[10],str[10],ft[10],tat[10],wt[10];
float avg1=0,avg2=0;
printf("enter the number of processes and time quantum");
scanf("%d%d",&n,&tq);
printf("enter the process number and service time");
for(i=0;i<n;i++)
{
scanf("%d%d",&p[i],&st[i]);
}
for(i=0;i<n;i++)
{
b[i]=st[i];
}
str[0]=0;
for(i=1;i<n;i++)
{
str[i]=str[i-1]+tq;
}
for(i=0;i<n;i++)
{
while(b[i]!=0)
{
for(j=0;j<n;j++)
{
if(b[j]==0)
{
continue;
}
if(b[j]>tq)
{
b[j]=b[j]-tq;
time=time+tq;
}
else
{
time=time+b[j];
b[j]=0;
ft[j]=time;
}
}
}
}
for(i=0;i<n;i++)
{
tat[i]=ft[i];
wt[i]=ft[i]-st[i];
avg1=avg1+tat[i];
avg2=avg2+wt[i];
}
printf("\n pnost\t ft \t tat\t wt");
for(i=0;i<n;i++)
{
printf("\n %d\t %d\t %d\t %d\t %d\t ",p[i],st[i],ft[i],tat[i],wt[i]);
}
printf("\n average tat is %f\n average wt is %f",(avg1/n),(avg2/n));
}
OUTPUT:
Pno st ft tat wt
1 24 30 30 6
2 3 7 7 4
3 3 10 10 7
Averagetat is 15.666667
Averagewt is 5.666667
Description: A fork system call creates a child process that is a clone of the parent.The child process
may execute a different program in its context with a separate exec() system call.Parent may want to
wait for children to finish by calling wait function.The wait() function suspends execution of its
calling process untilstatus information is available for a terminated child process, or a signal is
received.The exit() function is used to terminate the calling process immediately.
Program:
#include<stdio.h>
int main()
{
int p;
int status;
p=fork();
switch(p){
case-1:
perror("fork");
exit(1);
case0:
printf(“child process”);
break;
default:
wait(&status);
printf(“parent process”);
break;
}
return0;
}
OUTPUT:
Child process parent process
#include<stdio.h>
int main()
{
pid_t child;
int status;
child= fork();
switch(child){
case-1:
perror("fork");
exit(1);
case0:
printf("child process”);
break;
default:
wait(&status);
printf("parent process”);
break;
}
return0;
}
OUTPUT:
Child process parent process
#include <stdio.h>
int main()
{
int p;
p=fork();
switch(p)
{
case -1: exit(1); // fork() error.
case 0: // Child process.
if( execl("/bin/ls","ls",NULL) == -1)
{
perror("execl");
exit(1);
}
break;
default:
printf(“parent process”);
break;
}
}
OUTPUT:
F1.c f3.c file1.c parent process
Program:
#include<stdio.h>
#include<stdio.h>
main()
{
intpr[50],size[50],nba[50],ifm[50];
intm,b,bs,n,i,j,count=0;
printf("enter total memory size: ");
scanf("%d",&m);
printf("enter number of blocks: ");
scanf("%d",&b);
bs=m/b;
printf("block size is: %d\n",bs);
printf("enter number of processes: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
pr[i]=i+1;
printf("enter process %d size: ",i+1);
scanf("%d",&size[i]);
if(size[i]>m)
{
count=1;
break;
}
nba[i]=size[i]/bs;
if((size[i]%bs)!=0)
nba[i]=nba[i]+1;
ifm[i]=(nba[i]*bs)-size[i];
m=m-size[i];
}
printf("\nProcess \t Size \t No.of-blocksalloted \t internal-fragementation\n");
for(j=0;j<i;j++)
{
printf("p%d \t\t %d \t\t %d \t\t\t %d\n",pr[j],size[j],nba[j],ifm[j]);
}
if(count==1)
printf("insufficient memory for remaining processes");
}
OUTPUT :
Program:
#include<stdio.h>
main()
{
intpr[50],size[50],rm[50];
intm,b,bs,n,i,j,count=0;
printf("enter total memory size: ");
scanf("%d",&m);
printf("enter number of blocks: ");
scanf("%d",&b);
bs=m/b;
printf("block size is: %d\n",bs);
printf("enter number of processes: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
pr[i]=i+1;
printf("enter process%d size: ",i+1);
scanf("%d",&size[i]);
if(size[i]>m)
{
count=1;
break;
}
m=m-size[i];
rm[i]=m;
}
printf("\npr\tsize\trm\n");
for(j=0;j<i;j++)
printf("p%d\t%d\t%d\n",pr[j],size[j],rm[j]);
if(count==1)
printf("insufficient memory for remaining processes\n");
printf("External fragmentation is : %d\n",m);
}
OUTPUT :-
pr size rm
p1 50 750
p2 150 600
p3 200 400
External fragmentation is : 400
8.Simulate Bankers Algorithm for Dead Lock Avoidance.
Description:-
Deadlock Definition
A set of processes is deadlocked if each process in the set is waiting for an eventthat only
another process in the set can cause (including itself).Waiting for an event could be:
Waiting for access to a critical section
1. Waiting for a resource Note that it is usually a non-preemptable
(resource).Preemptable resources can be yanked away and given to another.
Conditions for Deadlock
1. Mutual exclusion: resources cannot be shared.
2. Hold and wait:processes request resources incrementally, and hold on to whatthey've
got.
3. No preemption: resources cannot be forcibly taken from processes.
4. Circular wait: circular chain of waiting, in which each process is waiting for
aresource held by the next process in the chain.
Strategies for dealing with Deadlock
1. Ignore the problem altogether
2. Detection and recovery
3. Avoidance by careful resource allocation
4. Prevention by structurally negating one of the four necessary conditions.
Deadlock Avoidance
Avoid actions that may lead to a deadlock. Think of it as a state machine movingfrom one
state to another as each instruction is executed.
Safe State:
Safe state is one where
1. It is not a deadlocked state
2. There is some sequence by which all requests can be satisfied.
To avoid deadlocks, we try to make only those transitions that will take you from onesafe
state to another. We avoid transitions to unsafe state (a state that is notdeadlocked, and is not
safe)
eg.Total # of instances of resource = 12(Max, Allocated, Still Needs)
P0 (10, 5, 5) P1 (4, 2, 2) P2 (9, 2, 7)
Free = 3 - Safe
The sequence is a reducible sequencethe first state is safe.
What if P2 requests 1 more and is allocated 1 more instance?
- results in Unsafe state
So do not allow P2's request to be satisfied.
Program:
#include<stdio.h>
#include<conio.h>
int C[4][3],A[4][3],RQ[4][3],V[3],R[3],K[4],sum=0,np,nr;
main()
{
void fun();
int i,j,count=0,pcount=0;
clrscr();
printf("\nEnter the total number of resources : ");
scanf("\n%d",&nr);
for(i=0;i<nr;i++)
{
printf("\nEnter the no of resources int R%d : ",i+1);
scanf("%d",&R[i]);
}
printf("\nEnter the no of processes to be executed : ");
scanf("%d",&np);
printf("\nEnter the claim matrix:\n");
for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&C[i][j]);
printf("\nEnter the allocation matrix:\n");
for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&A[i][j]);
for(i=0;i<np;i++)
for(j=0;j<nr;j++)
RQ[i][j] = C[i][j] - A[i][j];
/* FINDING THE REQUIRED RESOURCES MATRIX(i.e., C-A) */
fun();
for(i=0;i<np;i++)
{
count=0;
f(K[i] == i+1)
continue; /* FOR SKIPPING THE PROCESSES(i.e., ROWS) WHICH
WERE ALREADY EXECUTED */
for(j=0;j<nr;j++)
{
if(V[j] >= RQ[i][j])
count++;
}
if(count == nr)
{
K[i] = i+1;
for(j=0;j<nr;j++)
C[i][j] = A[i][j] = RQ[i][j] = 0;
pcount++;
count = 0;
i=-1;
fun();
}
}
if(pcount == np)
printf("\nThere is no chance of deadlock.\nIt is a safe state.");
else
printf("\nThere is a chance of deadlock.\nIt isn't a safe state.");
getch();
}
void fun()
{
int i1,j1;
for(i1=0;i1<nr;i1++)
{
for(j1=0;j1<np;j1++)
{
sum = sum + A[j1][i1];
}
V[i1] = R[i1] - sum;
sum = 0;
}
}
OUTPUT:
Description:Difference from avoidance is that here, the system itself is built in such a way that there
are no deadlocks.Make sure at least one of the 4 deadlock conditions is never satisfied. This may
however be even more conservative than deadlock avoidance strategy.
Attacking Mutex condition
Never grant exclusive access. but this may not be possible for several
resources.
Attacking preemption
#include<stdio.h>
#include<conio.h>
main()
{
int cl[10][10],al[10][10],av[10],i,j,k,m,n,c,ne[10][10],flag=0;
clrscr();
printf("\nEnter the matrix");
scanf("%d %d",&m,&n);
printf("\nEnter the claim matrix");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&cl[i][j]);
}
}
printf("\nEnter allocated matrix");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&al[i][j]);
}
}
printf("\nThe need matrix");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
ne[i][j]=cl[i][j]-al[i][j];
printf("\t%d",ne[i][j]);
}
printf("\n");
}
printf("\nEnter avaliable matrix");
for(i=0;i<3;i++)
scanf("%d",av[i]);
printf("Claim matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%d",cl[i][j]);
}
printf("\n");
}
printf("\n allocated matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%d",al[i][j]);
}
printf("\n");
}
printf(" available matrix:\n");
for(i=0;i<3;i++)
{
printf("\t%d",av[i]);
}
for(k=0;k<m;k++)
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(av[j]>=ne[i][j])
flag=1;
else break;
if(flag==1&& j==n-1)goto a;
}
}a:
if(flag==0)
{
printf("unsafestate");
}if(flag==1)
{
flag=0;
for(i=0;i<m;i++)
{
for(j=0;j<n;i++)
{
av[j]+=al[i][j];
l[i][j]=1;
}
}
printf("\n safe state");
for(i=0;i<n;i++)
printf("\t available matrix:%d",av[i]);
}
}
OUTPUT:
Enter the claim matrix:3 2 2 6 1 3 3 1 4 4 2 2
Enter allocated matrix:1 0 0 5 1 1 2 1 1 0 0 2
The need matrix:
222
102
103
420
Enter available matrix1 1 2
Claim matrix:
322
613
314
422
Allocated matrix:
100
511
211
002
Available matrix:
1 1 2 Safe State
10. Simulate the following page replacement algorithm
a)FIFO Page Replacement
Description:A FIFO replacement algorithm associates with each page the time when that page was
brought into memory. When a page must be replaced, the oldest page is chosen. We can create a
FIFO queue to hold all pages in memory. We replace the page at the head of the queue. When a page
is brought into memory, we insert it at the tail of the queue.
Program:
main()
{
inti,j,n,a[50],frame[10],no,k,avail,count=0;
printf("\n ENTER THE NUMBER OF PAGES:\n");
scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBERS :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
printf("ref string\t page frames\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("No.ofPage Faults %d",count);
}
OUTPUT:
ENTER THE NUMBER OF PAGES: 20
ENTER THE PAGE NUMBERS :
70120304230321201701
ENTER THE NUMBER OF FRAMES :3
ref string page frames
7 7 -1 -1
0 7 0 -1
1 7 0 1
2 2 0 1
0
3 2 3 1
0 2 3 0
4 4 3 0
2 4 2 0
3 4 2 3
0 0 2 3
3
2
1 0 1 3
2 0 1 2
0
1
7 7 1 2
0 7 0 2
1 7 0 1
Description:If we will replace the page that has not been used for the longest period of time. This
approach is the least recently used algorithm. By the principle of locality, this should be the page
least likely to be referenced in the near future.
Program:
#include<stdio.h>
#include<conio.h>
intfr[3];
main()
{
void display();
int index,k,l,flag1=0,flag2=0,pf=0,frsize,i,j,fs[3],n,p[20];
printf("\nenter length of string\n");
scanf("%d",&n);
printf("\n enter ref string\n");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("\n enter frame size");
scanf("%d",&frsize);
for(i=0;i<frsize;i++)
{
fr[i]=-1;
}
for(j=0;j<n;j++)
{
flag1=0,flag2=0;
for(i=0;i<frsize;i++)
{
if(fr[i]==p[j])
{
flag1=1;
flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<frsize;i++)
{
if(fr[i]==-1)
{ pf++;
fr[i]=p[j];
flag2=1;
break;
}
}
}
if(flag2==0)
{
for(i=0;i<frsize;i++)
fs[i]=0;
for(k=j-1,l=1;l<=frsize-1;l++,k--)
{
for(i=0;i<frsize;i++)
{
if(fr[i]==p[k])
fs[i]=1;
}
}
for(i=0;i<frsize;i++)
{
if(fs[i]==0)
index=i;
}
fr[index]=p[j];
pf++;
}
display();
}
printf("\n no of page faults :%d",pf);
}
void display()
{
int i;
printf("\n");
for(i=0;i<3;i++)
printf("\t%d",fr[i]);
}
OUTPUT:
Description: The least frequently used page (LFU). Since LFU tracks the usage count of pages, it
will take longer to replace pages with high count values, even if those pages are no longer in use.
Program:
#include<string.h>
#include<stdio.h>
int i,j=1,s,k,l,re[30],p[10],ch,no,nr,c,a1=0,a,line=6,nk;
struct
{
int st,l,ps,pos;
}opr;
main()
{
clrscr();
printf("Enter length of reference string:");
scanf("%d",&nr);
printf(" Enter reference string:");
for(i=1;i<=nr;i++)
scanf("%d",&re[i]);
printf("\n Enter number of frames:");
scanf("%d",&no);
clrscr();
for(i=1;i<=no;i++)
p[i]=-1;
opr.st=100;
for(i=1;i<=nr;i++)
{
a1=0;
opr.st=100;
opr.pos=100;
for(c=1;c<=no;c++)
if(re[i]==p[c])
a1++;
if(a1==0)
{
if(j<=no)
{
p[j]=re[i];
j++;
}
else
{
for(k=1;k<=no;k++)
{
a=0;
for(ch=i-1;ch>0;ch--)
{
if(p[k]==re[ch])
{
a++;
nk=ch;
}
}
if(a>1)
{
if(opr.st>a)
{
opr.st=a;
opr.ps=k;
}
else
if(opr.st==a)
{
if(opr.pos>ch)
opr.ps=k;
}
}
else
if(a==1)
{
if(opr.pos>nk)
{
opr.pos=nk;
opr.ps=k;
opr.st=a;
}
}
}
p[(opr.ps)]=re[i];
}
}
display(no,p,i);
}
printf("\n");
}
display(int no,int p[],int i)
{
int k;
printf("\n%d",re[i]);
gotoxy(25,line++);
for(k=1;k<=no;k++)
{
printf(" ");
if(p[k]!=-1)
printf("%d",p[k]);
else
printf(" ");
}
OUTPUT:
7 -1 -1
7 0 -1
7 0 1
2 0 1
2 0 1
2 0 3
2 0 3
4 0 3
4 0 2
4 3 2
0 3 2
0 3 2
0 3 2
1 3 2
1 3 2
1 0 2
1 0 2
1 0 7
1 0 7
1 0 7
Description: The contiguous-allocation method requires each file to occupy a set of contiguous
blocks on the disk. Disk addresses define a linear ordering on the disk. Accessing a file that has been
allocated contiguously is easy. For sequential access, the file system remembers the disk address of
the last block referenced and when necessary reads the next block.
Prpgram:
#include<stdio.h>
#include<string.h>
main()
{
inti,j,n,size[50],sblock[20],eblock[20];
char name[50];
printf("Enter no of files");
scanf("%d",&n);
printf("Enter file name and size and startblock");
for(i=0;i<n;i++)
{
scanf(" %c %d %d",&name[i],&size[i],&sblock[i]);
}
for(i=0;i<n;i++)
{eblock[i]=sblock[i]+size[i];
}
printf("file allocation table\n");
printf("name size startblockendblock\n");
for(i=0;i<n;i++)
{
printf("%c \t%d\t",name[i],size[i]);
printf("%d \t\t%d",sblock[i],eblock[i]);
printf("\n");
}
}
OUTPUT:
Enter no of files3
Enter file name and size and startblocka 3 0
b 5 10
c 4 18
file allocation table
name size startblock endblock
a 3 0 3
b 5 10 15
c 4 18 22
Description:
Each file has its own index block, which is an array of disk-block addresses. The ith entry in
the index block points to the ith block of the file. The directory contains the address of the index
block. To read the ith block, we use the pointer in the ith index-block entry to find and read the
desired block. When the file is created, all pointers in the index block are set to nil. When the ith
block is first written, a block is obtained from the free-space manager, and its address is put in the ith
index-block entry.
Program:
#include<stdio.h>
#include<string.h>
main()
{
inti,j,n,size[50],block[20][20],ib;
char name[50];
printf("Enter no of files");
scanf("%d",&n);
printf("Enter file name and size");
for(i=0;i<n;i++)
{
scanf(" %c %d",&name[i],&size[i]);
}
printf("Enter Index block");
scanf("%d",&ib);
printf("enter index block sequence for each file");
for(i=0;i<n;i++)
{
block[i][0]=ib;
for(j=1;j<size[i];j++)
{
scanf("%d",&block[i][j]);
}
}
printf("file allocation table\n");
printf("name size start block\n");
for(i=0;i<n;i++)
{
printf("%c \t%d\t",name[i],size[i]);
for(j=0;j<size[i];j++)
{
printf("%d-",block[i][j]);
}
printf("\n");
}
}
OUTPUT:
Enter no of files3
Enter file name and size a 3
b3
c3
Enter Index block5
enter index block sequence for each file1 4
26
39
file allocation table
name size start block
a 3 5-1-4
b 3 5-2-6
c 3 5-3-9
11. Simulate the following file allocation strategy
c) Linked file
Description:With linked allocation, each file is a linked list of disk block; the disk blocks may be
scattered anywhere on the disk. The directory contains a pointer to the first and last blocks of the
file. In linked allocation, each directory entry has a pointer to the first disk block of the file. This
pointer is initialized to nil to signify an empty file. A write to the file causes a free block to be found
via the free space management system, and this new block is then written to, and is linked to the end
of the file. To read a file, we simply read blocks by following the pointers from block to block.
There is no external fragmentation with linked allocation.
Program:
#include<stdio.h>
#include<string.h>
main()
{
inti,j,n,size[50],block[20][20];
char name[50];
printf("Enter no of files");
scanf("%d",&n);
printf("Enter file name and size");
for(i=0;i<n;i++)
{
scanf(" %c %d",&name[i],&size[i]);
}
printf("enter block sequence for each file");
for(i=0;i<n;i++)
{
for(j=0;j<size[i];j++)
{
scanf("%d",&block[i][j]);
}
}
printf("file allocation table\n");
printf("name size blocks\n");
for(i=0;i<n;i++)
{
printf("%c \t%d\t",name[i],size[i]);
for(j=0;j<size[i];j++)
{
printf("%d-",block[i][j]);
}
printf("\n");
}
}
OUTPUT:
Enter no of files3
Enter file name and size a 2
b2
c2
enter block sequence for each file 1 4
26
39
file allocation table
name size blocks
a 2 1-4
b 2 2-6
c 2 3-9
Program:
#include <stdio.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#define SEGSIZE 100
int main(int argc, char *argv[ ])
{
int shmid,cntr;
key_t key;
char *segptr;
char buff[ ]=”Hello world”;
key=ftok(“.”,’s’);
if((shmid=shmget(key, SEGSIZE, IPC_CREAT | IPC_EXCL | 0666))= = -1)
{
if((shmid=shmget(key,SEGSIZE,0))= = -1)
{
perror(“shmget”);
exit(1);
}
}
else
{
printf(“Creating a new shared memory seg \n”);
printf(“SHMID:%d”, shmid);
}
system(“ipcs –m”);
if((segptr=shmat(shmid,0,0))==(char*)-1)
{
perror(“shmat”);
exit(1);
}
printf(“Writing data to shared memory…\n”);
strcpy(segptr,buff);
printf(“DONE\n”);
printf(“Reading data from shared memory…\n”);
printf(“DATA:-%s\n”,segptr);
printf(“DONE\n”);
print(“Removing shared memory Segment…\n”);
if(shmctl(shmid,IPC_RMID,0)= = -1)
printf(“Can’t Remove Shared memory Segment…\n”);
else
printf(“Removed Successfully”);
}
OUTPUT:
Description: a semaphore is a variable or abstract data type that is used for controlling access, by
multiple processes, to a common resource in a concurrent system such as a multiprogramming
operating system. Semaphores are a useful tool in the prevention of race conditions.Semaphores
which allow an arbitrary resource count are called counting semaphores, while semaphores which
are restricted to the values 0 and 1 (or locked/unlocked, unavailable/available) are called binary
semaphores.
Program:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<time.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#define NUM_LOOPS 20
int main(int argc,char* argv[])
{
int sem_set_id;
int sem_val;
int child_pid;
int i;
struct sembuf sem_op;
int rc;
struct timespec delay;
sem_set_id=semget(IPC_PRIVATE,1,0600);
if(sem_set_id==-1)
{
perror("main:semget");
exit(1);
}
printf("semaphore set created,semaphore set id '%d'\n",sem_set_id);
sem_val=0;
rc=semctl(sem_set_id,0,SETVAL,sem_val);
child_pid=fork();
switch(child_pid)
{
case-1:
perror("fork");
exit(1);
case 0:
for(i=0;i<NUM_LOOPS;i++)
{
sem_op.sem_num=0;
sem_op.sem_op=-1;
sem_op.sem_flg=0;
semop(sem_set_id,& sem_op,1);
printf("consumer:'%d'\n",i);
fflush(stdout);
sleep(3);
}
break;
default:
for(i=0;i<NUM_LOOPS;i++)
{
printf("producer:'%d'\n",i);
fflush(stdout);
sem_op.sem_num=0;
sem_op.sem_op=1;
sem_op.sem_flg=0;
semop(sem_set_id,&sem_op,1);
sleep(2);
if(rand()>3*(RAND_MAX/4))
{
delay.tv_sec=0;
delay.tv_nsec=10;
nanosleep(&delay,NULL);
}
}
break;
}
return 0;
}
OUTPUT:
14) Write a c program to create a thread using pthreads library and let it run its
function.
Description: The POSIX thread (pthreads)librariesare a standards based thread API for C/C++. It
allows one to spawn a new concurrent process flow. It is most effective on multi-processor or multi-
core systems where the process flow can be scheduled to run on another processor thus gaining
speed through parallel or distributed processing. Threads require less overhead than "forking" or
spawning a new process because the system does not initialize a new system virtual memory space
and environment for the process. While most effective on a multiprocessor system, gains are also
found on uniprocessor systems which exploit latency in I/O and other system functions which may
halt process execution. A thread is spawned by defining a function and it's arguments which will be
processed in the thread. The purpose of using the POSIX thread library in your software is to execute
software faster.
Program:
#include <pthread.h>
#include <stdio.h>
void *inc_x(void *x_void_ptr)
{
int *x_ptr = (int *)x_void_ptr;
while(++(*x_ptr) < 100);
printf("x increment finished\n");
return NULL;
}
int main()
{
int x = 0, y = 0;
printf("x: %d, y: %d\n", x, y);
pthread_t inc_x_thread;
if(pthread_create(&inc_x_thread, NULL, inc_x, &x))
{
fprintf(stderr, "Error creating thread\n");
return 1;
}
while(++y < 100);
printf("y increment finished\n");
if(pthread_join(inc_x_thread, NULL))
{
fprintf(stderr, "Error joining thread\n");
return 2;
}
printf("x: %d, y: %d\n", x, y);
return 0;
}
OUTPUT:
x: 0, y:0
y increment finished
x increment finished
x: 100, y: 100
15.Write a C program to illustrate concurrent execution of threads using
pthreads library.
Description: Concurrent programming in a general sense to refer to environments in which the tasks
we define can occur in any order. One task can occur before or after another, and some or all tasks
can be performed at the same time. We'll use parallel programming to specifically refer to the
simultaneous execution of concurrent tasks on different processors. Thus, all parallel programming
is concurrent, but not all concurrent programming is parallel. Whether the threads actually run in
parallel is a function of the operating system and hardware on which they run. Because Pthreads was
designed in this way, a Pthreads program can run without modification on uniprocessor as well as
multiprocessor systems.
Program:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *mythread1(void *vargp)
{
int i;
printf("thread1\n");
for(i=1;i<=10;i++)
printf("i=%d\n",i);
printf("exit from thread1\n");
return NULL;
}
void *mythread2(void *vargp)
{
int j;
printf("thread2 \n");
for(j=1;j<=10;j++)
printf("j=%d\n",j);
printf("Exit from thread2\n");
return NULL;
}
int main()
{
pthread_t tid;
printf("before thread\n");
pthread_create(&tid,NULL,mythread1,NULL);
pthread_create(&tid,NULL,mythread2,NULL);
pthread_join(tid,NULL);
pthread_join(tid,NULL);
exit(0);
}
OUT PUT :
$ cc w8.c – l pthread
$./a.out
thread1
i=1
i=2;
i=3
thread2
j=1
j=2
j=3
j=4
j=5
j=6
j=7
j=8
i=4
i=5
i=6
i=7
i=8
i=9
i=10
exit from thread1
j=9
j=10
exit from thread2