Professional Documents
Culture Documents
F COLLEGE OF ENGINEERING
AND TECHNOLOGY
PALWAL, HARYANA
CODE: PCC-CS-406
1. CLS:- (Clear the screen) This command is used to clear the screen or
wipe out every thing written on the screen.
2. DIR:- (Directory) Dir command is used for listing files and directories
present in the current disk.
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
Output:-
C:\>VER
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
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.
7. COPY CON:- This command gives the facility to create a new text file.
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.
8. TYPE:- This command is used to display the contents or text of any file
to the display device.
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.
10. REN:- (Rename) This command is used to change the name of any file
or directory.
11. DEL:- This command is used for erasing any file from the disk.
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.
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:\>
15. PATH:- This command is used for display or sets directories for
executable files.
NOTE:- If we need any help for above DOS commands the we put a '/?'
symbol after writting the command at DOS prompt .
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:
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.
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.
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.
C:\>
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.
---------- gulab.txt
A clock in a office can never get stolen
11. ATTRIB:- Sets the various type of attribute to a file. Like Read only,
Archive, Hidden and System attribute.
12. LABEL:- If you are not happy with the volume label of hard disk, you
can change it.
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.
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
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).
Although the steps may differ depending on the distribution that you’re using, you
can usually find the command line in the Utilities section.
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.
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.
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.
7. mkdir command
Use mkdir command to make a new directory — if you type mkdir Music it will
create a directory called Music.
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.
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.
As an example, find /home/ -name notes.txt command will search for a file
called notes.txt within the home directory and its subdirectories.
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.
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.
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.
There is a total of sixty-four signals that you can use, but people usually only use two
signals:
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:
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:
$ 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).
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
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
CATEGORIES:-
• Ordinary file
• Directory file
• Device file
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
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.
Options:-
➢ It renames a file.
➢ It moves a group of files to a different directory.
$ wc filename
OPTIONS:-
i. wc –l filename
ii. wc –w filename
iii. wc –c filename
iv. wc –l-c filename
To files are compared byte by byte and the location of first mismatch is echoed to the
screen.
OPTIONS:-
i) $ls-l: listing file attributes like permissions, size,ownership.
Relative permissions:-
File permissions:-
r- read
w- write
x- execute
ABSOLUTE PERMISSIONS:-
10. head:- used to display the no of lines of all files. By default it displays 10
lines from starting.
Output:-
1. hello
2. gud afternoon
3. jmdsfk
Option:- $grep –i pattern filename (it ignores uppercase and lower case letters)
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
$ 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
Script:-
Output:-
$ sh prog7
current date and time isThu Apr 1 09:23:12 EDT 2010
Script:-
pattern=$1
filename=$2
echo "pattern=" $pattern
echo "filename=" $filename
grep "$pattern" $filename
Output:-
Script:-
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
Script:-
Output:-
Script:-
Output:-
$ sh prog11 56 34 74
the greatest number is 74
PROGRAM-7
#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
#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);
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;
avg_tat=(float)total/n;
printf("nnAverage Waiting Time=%f",avg_wt);
printf("nAverage Turnaround Time=%fn",avg_tat);
}
Output:
PROGRAM-9
#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
#include<stdio.h>
struct process
{
int WT,AT,BT,TAT,PT;
};
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);
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;
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
#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
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
#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
#include<semaphore.h>
#include<stdio.h>
#include<stdlib.h>
sem_t x,y;
pthread_t tid;
pthread_t writerthreads[100],readerthreads[100];
int readercount;
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
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
// Function prototypes…
void *customer(void *num);
void *barber(void *);