Está en la página 1de 58

LINUX COMMANDS

Ex:No:1
Aim:

man,cd,cd .,cd ..,ls,ls-a,pwd commands

To execute the following commands and write down the results and use of each Command:(i)man (II)cd (iii)cd. (iv)cd .. (v)ls, ls a (vi)pwd.

Objectives:
i)man :
Used to view the manual pages dealing with particular command.

ii)cd

:
Used to change from one directory to another directory.

iii)cd . :
Used to display the current working directory.

iv)cd .. :
Used to move the previous directory.

v)ls :
Used to list out all Files and directory .

vi)ls-a :
Used to list all files including the hidden files with dot(.).

vii)pwd :
Used to display current working directory.

Syntax used:
i. man
$man <anyone command name>

ii. cd
$cd <directory name>

iii. cd .
$cd .

iv.cd ..
$cd..

v. ls
$ls

OperatingSystem

vi. ls-a
$ls-a

vii. pwd
$pwd

Output:
(i)man command:
[su@localhost pgm]$ man cat CAT(1) NAME cat concatenate files and print on the standard output SYNOPSIS cat [OPTION] [FILE]... DESCRIPTION Concatenate FILE(s), or standard input, to standard output. display TAB characters as ^I output version information and exit With no FILE, or when FILE is , read standard input. User Commands CAT(1)

(ii)cd command:
[su@localhost pgm]$ mkdir java [su@localhost pgm]$ cd java [su@localhost java]$

(iii)cd. Command:
[su@localhost pgm]$cd . [su@localhost pgm]$

(iv)cd ..command:
[su@localhost pgm]$ cd java [su@localhost java]$ cd .. [su@localhost pgm]$

OperatingSystem

(v)ls,ls a command:
a)ls:
[su@localhost pgm]$ ls a.out consume.c calc fcfs.c fifc.c java name.txt upperlower upperLower array deadlock.c intro1.txt [su@localhost pgm]$ maxmin sum.c

intro5.text min.sh upper

b)ls a:
[su@localhost pgm]$ ls -a . .. array calc deadlock.c intro1.txt fcfs.c maxmin sum.c upperLower intro5.text min.sh java upper a.out consume.c fifc.c name.txt upperlower

(vi)pwd command:
[su@localhost pgm]$ pwd /home/su/pgm [su@localhost pgm]$

Result:
Thus the above commands were executed successfully.

OperatingSystem

Viva Questions:
1. Define Operating System.
The operating system is a set of software programs normally supplied along with the hardware for the efficient use of machine.It is used to communicate between the hardware and the software.It act as a bridge between the hardware and the software.

WhatismeantbyLinuxoperatingsystem?
Linux is a clone of Unix operating system.Linux is a complete multiuserand multitasking operting system

2. What are the different kind of operting systems are available.


i) ii) iii) iv) MS-DOS Windows family UNIX LINUX

3. What is the use of Telnet?


Telnet is a protocol for logging into remote machines. Through

Telnet,anadministratororanotherusercanaccesssomeoneelse's computerremotely.

4. Features of Linux:
i) ii) iii) iv) v) Modularity Multitasking Multi-User Communication Transportability

OperatingSystem

Ex: no: 2(a)


Aim :

Creating and Deleting a directory

To make your own subdirectories called uni and linu in your home directory.Then delete the sub directory called uni and find the system devices

Objectives: i)mkdir:
Used to create a new directory.

ii)rmdir:
Used to remove a directory.

Syntax : mkdir:
$mkdir <directory name>

rmdir:
$rmdir <directory name>

Output: Creating Directory:


[su@localhost /]$ cd home [su@localhost home]$ mkdir uni [su@localhost home]$ cd uni [su@localhost uni]$ cd .. [su@localhost home]$ mkdir linu [su@localhost home]$ cd linu [su@localhost linu]$ cd ..

Removing directory:
[su@localhost home]$ rmdir uni [su@localhost home]$ cd uni -bash: cd: uni: No such file or directory [su@localhost home]$

Result:
Thus the above commands were executed successfully.

OperatingSystem

Ex.no:2(b)
Aim:

Explore the file system

To explore the file system,write what is there in /bin,/usr/bin,/sbin/tmp and /boot.Find and list the Devices that are available in your system.

Objectives:
i) ii) iii) /bin:
This directory holds users home directories.

/usr/bin:
This directory holds users oriented linux programe.

/sbin/tmp:
/sbin holds system files that are usually run automatically by the linux system. /tmp is the canonical repository for temporary files and data.

iv) v) vi) vii)

/boot:
It contains files requires to boot the system.

Cd:
Used to change the directory.

ls:
Used to display all files and directories.

Pwd:
Print the current working working directory.

Syntax :
cd command: $cd <directory name> ls command: $ls pwd command: $pwd

Output:
a) /bin
[su@localhost /]$ cd bin [su@localhost bin]$ pwd /bin

OperatingSystem


[su@localhost bin]$ ls arch ash ash.static awk basename bash unicode_start cut date dd dmesg doexec gawk gettext grep gtar gunzip ls mail mkdir mknod mktemp more sed red rm rmdir rpm rvi tar tcsh touch true umount rview uname

aumix-minimal df

dnsdomainname gzip

hostname mount

b) /usr/bin
[su@localhost\]$cd usr [su@localhost usr]$cd bin [su@localhost bin]$ pwd /usr/bin [su@localhost bin]$ls kmenuedit kmessedwords kmid kmidi kmines kminspector ttfprint ttindex ttmkfdir tty tunctl tuxracer

c) /sbin/tmp:
[su@localhost sbin]$ cd tmp [su@localhost tmp]$ pwd /sbin/tmp [su@localhost tmp]$ ls orbit-root scrollkeeper-tempfile.0 ssh-XXhjLRpu ssh-XXrRZwNw ssh-XxzmVzhi

d) /boot
[su@localhost /]$ cd boot [su@localhost boot]$ pwd /boot [su@localhost boot]$ ls boot.b chain.b config-2.4.18-14 config-2.4.18-14debug module-info-2.4.18-14smp module-info-2.4.18-14uml os2_d.b System.map

OperatingSystem

To find the System devices:


[Stewaugh@localhostdev]$cd/ [Stewaugh@localhost/]$ls bindevhomelibmiscnetprocsbintmpvar bootetcinitrdlost+foundmntoptroottftpbootusr [Stewaugh@localhost/]$cddev [Stewaugh@localhostdev]$ls
OUTPUT:

hdl20ptyv7sdcc14sdep3sdhb6sgnurandom hdl21ptyv8sdcc15sdep4sdhb7sgousb hdl22ptyv9sdcc2sdep5sdhb8sgpvbi hdl23ptyvasdcc3sdep6sdhb9shmvbi0 hdl24ptyvbsdcc4sdep7sdhcsjcdvbi1 hdl25ptyvcsdcc5sdep8sdhc1smousevbi2 hdl26ptyvdsdcc6sdep9sdhc10smpte0vbi3 hdl27ptyvesdcc7sdeqsdhc11smpte1vcs hdl28ptyvfsdcc8sdeq1sdhc12smpte2vcs1 hdl29ptyw0sdcc9sdeq10sdhc13smpte3vcs10 hdl3ptyw1sdcdsdeq11sdhc14sndstatvcs11 hdl30ptyw2sdcd1sdeq12sdhc15socksysvcs12 hdl31ptyw3sdcd10sdeq13sdhc2sonycdvcs13 hdl32ptyw4sdcd11sdeq14sdhc3spxvcs14

Result:
Thus the files are explored using ls,cd and pwd commands successfully.

OperatingSystem

Viva Questions:
1. What are the commands available to display a certain number of lines on the screen?
a) head : To display the specified number of lines from the beginning of a file. head <option> <file name> Eg: head -2 flower.txt b) tail: To display the specified number of lines from the end of a file. tail <option> <file name>

2. Define Wildcard Characters.


Use special characters in the command instead of actual file names.These special characters are calles as wildcard characters. Character * ? [] Purpose Matches one or a string of charactes. Matches exactely one character. Matches exactly one of a specified character.

3. What are the filtes available in Linux?


i) ii) iii) iv) v) cat grep wc tr cut

4. grep:
The grep filter searches a file for a specified patten os charcters and displays all the lines that contain the patternThe patten that is searched for is referred to as a regular expression.The grep filter cannot be used without specifying a regular expression. grep regular_expression <file name>

OperatingSystem

Ex.No:3(a) Creating and Copying a File from one directory to other Directory
Aim:
To create and copy a file from one directory to another directory.

Objectives:
i) ii) iii) Cat > :
Used to create a new file.

Cat:
Used to view the contents of a file.

Cp:
Used to copy the file from source to destination.

Syntax:
a) Cat >:
$ cat > <file name>

b) Cat:
$ cat <file name>

c) cp:
$ cp r <source directory name> <destination directory name>

Output:
Creating a file: [su@localhost su]$ cat >intro4.text Hello I am the student of computer branch [8]+ Stopped Viewing a file: [su@localhost su]$ cat intro4.text Hello I am the student of computer branch [su@localhost su]$ pwd /home/su/su cat >intro4.text

OperatingSystem

10


Copying a file: [su@localhost su]$ cp intro4.text /home/su/pgm/intro5.text [su@localhost su]$ cd .. [su@localhost su]$ cd pgm [su@localhost pgm]$ cat intro5.text Hello I am the student of computer branch [su@localhost gm]$

Result:
Thus the above command were executed successfully.

OperatingSystem

11

Ex.No:3(b)
Aim:

Changing the file permission

To change the file permission using different commands.

Objectives:
chmod:
Used to change the file permission.

Syntax:
I)Chmod (Using symbolic mode): $chmod <group> <operation> <mode> <filename> Where Group u-user g-group o-other a-all Operation + assign permission - remove permission = assign absolute mode r read w-write x-execute

ii) chmod (using absolute mode): $chmod octalnumber filename Where Octalnumber 4 - read permission 2 - write permission 1 - execute permission 6 - read write permission

OperatingSystem

12

Output:
Chmod (Using symbolic mode): [su@localhost pgm]$ ls -l intro.text -rw-rw-r-1 su su 42 Apr 4 12:03 intro.text [su@localhost pgm]$ chmod u+rwx intro.text [su@localhost pgm]$ ls -l intro.text -rwxrw-r-1 su su 42 Apr 4 12:03 intro.text [su@localhost pgm]$ chmod g+wx intro.text [su@localhost pgm]$ ls -l intro.text -rwxrwxr-1 su su 42 Apr 4 12:03 intro.text [su@localhost pgm]$ chmod o-r intro.text [su@localhost pgm]$ ls -l intro.text -rwxrwx--1 su su 42 Apr 4 12:03 intro.text

Chmod (Using absolute mode): [su@localhost pgm]$ chmod 641 intro.text [su@localhost pgm]$ ls -l intro.text -rw-r----x 1 su su 42 Apr 4 12:03 intro.text [su@localhost pgm]$ chmod 000 intro.text [su@localhost pgm]$ ls -l intro.text ---------1 su su 42 Apr 4 12:03 intro.text [su@localhost pgm]$ chmod 261 intro.text [su@localhost pgm]$ ls -l intro.text --w-rw---x 1 su su 42 Apr 4 12:03 intro.text

Result:
Thus the above commands to change the file permission were executed successfully.

OperatingSystem

13

Ex.No:3(c)
Aim:

Usage of Find command

To display the name of all files in the home directory using find command.

Objectives:
find:
Used to display all files in the home directory.

Syntax: I)find
$find $find name * size +<file size in kilobyte (k)> Where * denotes to search all the files.

Output:
[su@localhost home]$ find ./su/su/intro3.text ./su/su/intro.text ./su/su/intro4.text ./su/su/lock.c ./su/su/a ./su/su/deadlockavoi.c ./su/su/deadlock.c ./su/su/deadlockavoidance ./su/su/deadlockavoidance.c ./su/.viminfz.tmp [su@localhost home]$ find -name '*' -size +500k [su@localhost home]$ find -name '*' -size +10k ./lost+found ./pgm/a.out ./suja/pg1 ./suja/pg1~ ./suja/OS lab.sxw ./a.out ./mbox [suja@localhost suja]$

OperatingSystem

14

Result:
Thus the find command was successfully executed and display all files in the home directory.

Viva Questions
1. clear:
It is used to Clears the terminal screen.

Syntax:
$ clear

2.

cmp:
Compares two files, reporting all discrepancies Syntax: $cmp file1 file2

3.

diff: Compares two files, reporting all discrepancies Syntax: $diff file1 file2

OperatingSystem

15

Ex:no:4(a)
Aim:

Use of finger and who commands

To use finger or who to get a list of users on the machine.

Objectives: i)finger:
It provides you with more complete information about the users who are logged in.

ii)who:
To see who is using the system.

Syntax:
i.Finger command: $finger (or) ii.who command: $who $finger <user name>

Output: Finger command:


[su@localhost pgm]$ finger Login root su Name root sumasu Tty *:0 pts/1 Idle Login Time Apr 4 09:22 Apr 4 09:52 (sys7.ceserver.local) Name: sumasuja Shell: /bin/bash Office Office Phone

[su@localhost home]$ finger su Login: su Directory: /home/su No mail. No Plan.

On since Thu Apr 17 09:06 (IST) on pts/1 from sys7.ceserver.local

Who command:
[su@localhost pgm]$ who root su su :0 pts/1 pts/0 Apr 4 09:22 Apr 4 09:52 (sys7.ceserver.local) Apr 19 11:49 (sys7.ceserver.local)

[su@localhost su]$ who am i [su@localhost pgm]$

Result:
Thus the who and finger commands were executed successfully.

OperatingSystem

16

Ex: no: 4(b) Add different Users and set their Passwords &
Permissions Aim:
To add a different users and set their passwords and change their permissions.

Objectives:
i) ii) iii) adduser:
To add a new user.

Passwd:
To set the password in the existing user.

Chmod :
Define the permission to the user.

Syntax:
i) Add a new user: $ useradd <user name> ii) Change password: $ passwd <user name> iii) Define Permissions: a)Chmod (Using symbolic mode): $chmod <group> <operation> <mode> <username> Group u-user g-group o-other a-all Operation + assign permission - remove permission = assign absolute mode r read w-write x-execute

b)chmod (using absolute mode): $chmod <octalnumber>< filename> Where Octalnumber 4 - read permission 2 - write permission 1 6 - execute permission - read write permission

OperatingSystem

17

Output
Add a new user: [root@localhost root]# useradd kala Change password: [root @localhost root]# passwd kala Changing password New password: BAD password: it is based on a dictionary word Retype new password: Passwd: all authentication token updated successfully. Define Permission: [root @localhost home]#ls l drwxrwxrwx admin drwxrwxrwx ce2850348 drwxrwxrwx ce2850325 drwx-----12:52 jj 3 kala kala 4096 Apr 17 drwx-----16:52 kala [root @localhost home]#chmod g+rx kala [root @localhost home]ls l drwxrwxrwx admin drwxrwxrwx ce2850348 drwxrwxrwx ce2850325 drwx-----12:52 jj 3 kala kala 4096 Apr 17 drwxr-x---16:52 kala [root @localhost home]#chmod 246 kala [root @localhost home]#ls -l drwxrwxrwx admin 3 admin admin 4096 Apr 2 12:17 3 jj jj 4096 Apr 22 3 ce2850325 users 4096 Apr 42 12:17 3 ce2850348 users 4096 Apr 3 12:41 3 admin admin 4096 Apr 2 12:17 3 jj jj 4096 Apr 22 3 ce2850325 users 4096 Apr 42 12:17 3 ce2850348 users 4096 Apr 3 12:41 3 admin admin 4096 Apr 2 12:17

OperatingSystem

18


drwxrwxrwx ce2850348 drwxrwxrwx ce2850325 drwx-----12:52 kala [root @localhost home]# jj 3 kala kala 4096 Apr 17 16:52 -w-rrw3 jj jj 4096 Apr 22 3 ce2850325 users 4096 Apr 42 12:17 3 ce2850348 users 4096 Apr 3 12:41

Result:
Thus the above commands to add a new user, chage therir password and change their permission were verified successfully.

OperatingSystem

19

Ex: no: 4(c)


Aim:

Delete the existing user

To delete a user that have already exist.

Objectives:
i) Userdel:
Used to delete a user.

Syntax:
$ userdel < user name >

Output:
[root@localhost root]# userdel kala

Result:
Thus the above command to delete the existing user was verified successfully.

Viva Questions:
1. Free:
Displays the amount of used and free system memory. Syntax: $free

2. Clear:
Clears the terminal screen. Syntax: $clear

3. W:
Prints the current system workers. Syntax: $w

OperatingSystem

20

Ex.No:5(a)Download files from remote machine to local host


Aim:
To try to access your account available at a remote machine and download a file from remote machine to local host.

Objective:
i) ii) cp :
To copy the file from one user to another.

Cat:
To view the content of the copied file.

Syntax:
cp:
$cp r <source file name> <destination file name>

cat:
$cat <file name>

Output:
[su@localhost home]$ cp -r /home/intro hh [su@localhost home]$ cat hh Welcome to M.S.P.V.L Polytechnic college.

Result:
Thus the above commands were executed successfully.

OperatingSystem

21

Ex.No:5(b) Create a Cron job that sends you a message after every 5minutes
Aim:
To create a cron job that sends you a message after every 5 minutes.

Objectives:
i) ii) iii) Crontab e:
To create a new crontab file.

Crontab l:
To display all the cron jobs.

Crontab r:
To remove the cron job.

Syntax:
Create a crontab file:
$crontab e

Display the cron job:


$crontab l

Remove the cron job:


$crontab r

Output
[su@localhost su]$ crontab -e [su@localhost su]$ crontab -l # DO NOT EDIT THIS FILE - edit the master and reinstall. # (/tmp/crontab.2392 installed on Mon Apr 21 11:12:09 2008) # (Cron version -- $Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp $) */2 * * * * echo "Hello" [su@localhost su]$ mail Mail version 8.1 6/6/93. Type ? for help. "/var/spool/mail/su": 30 messages 30 new >N 1 root@localhost.local Mon Apr 21 11:16 20/803 <su@localhost>" N 2 root@localhost.local Mon Apr 21 11:18 20/803 <su@localhost>" & Message 1: "Cron "Cron

OperatingSystem

22


From su@localhost.localdomain Mon Apr 21 11:16:32 2008 Date: Mon, 21 Apr 2008 11:16:01 +0530 From: root@localhost.localdomain (Cron Daemon) To: su@localhost.localdomain Subject: Cron <su@localhost> echo "Hello" X-Cron-Env: <SHELL=/bin/sh> X-Cron-Env: <HOME=/home/su> X-Cron-Env: <PATH=/usr/bin:/bin> X-Cron-Env: <LOGNAME=su> Hello & Message 2: From su@localhost.localdomain Mon Apr 21 11:18:32 2008 Date: Mon, 21 Apr 2008 11:21:00 +0530 From: root@localhost.localdomain (Cron Daemon) To: suja@localhost.localdomain Subject: Cron <su@localhost> echo "Hello" X-Cron-Env: <SHELL=/bin/sh> X-Cron-Env: <HOME=/home/su> X-Cron-Env: <PATH=/usr/bin:/bin> X-Cron-Env: <LOGNAME=su> Hello & At EOF [su@localhost su]$ crontab r [su@localhost su]$ crontab -l no crontab for su

Result:
Thus the above command to create a cron job that sends a mesage after every 5 minutes.

OperatingSystem

23

Ex.No:5(c)
Aim:

Use of wall command

To write a message to inform all users that they should shut down their machine after completing the lab exercise.

Objectives: Wall:
To broadcast a message to all users connected to the server.

Syntax: $wall
<Type your message here> Press Ctrl+d

Output:
[su@localhost su]$ wall They should shut down their machine after completing the lab exercise. [su@localhost su]$ Broadcast message from su (pts/0) (Mon Apr 21 15:01:22 2008): They should shut down their machine after completing the lab exercise.

Result:
Thus the program to broadcast a message to all users using wall command executed successfully.

OperatingSystem

24

SHELL PROGRAMS
Ex: No: 6(a)
Aim:
To write a program to find the factorial of a given number

Factorial of a given number

Procedure:
1) Create a new vi editor file. 2) Get the input number. 3) Set i=1 and fact=i 4) Check i less than n the fact=fact*i 5) Increment the variable i. 6) Repeat the steps up to this condition false(ie i<n) 7) Print the result.

Program:
#!bin/bash echo "Enter the number" read n i=1 fact=1 while [ $i -le $n ] do ((fact=$fact*$i)) ((i=$i + 1)) done echo "Factorial of $n is: $fact"

Output:
[root@localhost root]# bash factor Enter the number 6 Factorial of 6 is :720

Result:
Thus the program to find the factorial of the given number was executed successfully.

OperatingSystem

25

Ex.No:6(b) Sum of Odd/Even numbers from M to N


Aim:
Write a program to find the sum of odd/even numbers from M to N.

Procedure:
1) Create a new vi editor file. 2) Get the value of n and m 3) Initialize k=0 and p=0. 4) Find the modulo of the input series. 5) If the modulo output is zero the given number is odd else the number is even 6) Find the sum of odd and even numbers separately. 7) Print the result.

Program:
#!bin/bash echo "Enter the value of m" read m echo "Enter the value of n" read n k=0 p=0 while [ $m -le $n ] do ((t=m%2)) if [ $t -eq 0 ] then ((p=p+m)) else ((k=k+m)) fi ((m=m+1)) done echo "The sum of odd numbers are $k" echo "The sum of even numbers are $p"

OperatingSystem

26

Output:
[root@localhost root]# bash pg2 Enter the value of m 1 Enter the value of n 10 The sums of odd numbers are 25 The sums of even numbers are 30

Result:
Thus the program to find the odd or even of the given number was executed successfully

OperatingSystem

27

Viva Questions
1. What is meant by Text Editors?
A Text Editor is a program that enables you to create and modify text files. It provides a screen with a fixed line length and line numbers. You can type text line by line, navigate through the documents y using different commands and save the document.

2. What are Editors available with Linux?


i) ii) iii) iv) v) vi) vii) vi Editor vim Editor emacs Editor ed Editor red Editor joe Editor pico Editor

3. What is meant by vi Editor?


The vi Editor is a visual Editor used to create and edit text files,documents,and programs. The following command is used to invoke the vi Editor Vi Filename <Enter> 4. Commands used in the vi Editor

Commands
H L K J X :wq<Enter> :w<Enter>

Action
Moves the coucor to the previous character. Moves the cursor to the next character. Moves the cursor to the line above the current line. Moves the cursor to the line above the current line. Deletes the character at the current cursor position. Saves all the changes and quits the vi Editor. Saves the File.

OperatingSystem

28


:q<Enter> :e <File Name> <Enter> :w! <File Name> <Enter> :! <command Name> <Enter> :r <File name><Enter> Quits without saving File. Opens the specified File. Forcefully writes to the specified File. Executes a shell command. Reads and Inserts the contents of the file after the current file.

5. Insert and Replce commands:

Commands
A A I I O O character.

Action
Enables you to append text after the current

Enables you to append text at the end of the file. Enables you to insert text before the current character. Enables you to insert text at the end of the file. Inserts a blank line below the current line, and allows you to inser text. Inserts a blank line below the current line, and allows you to inser text.

OperatingSystem

29

Ex: No:7(a) Aim:

Find the greatest of given three numbers


given three numbers.

Write a program to find greatest of

Procedure:
1) Create a new vi editor file. 2) Get the 3 input numbers. 3) Get the value for three variables. 4) Find the greatest value among them, using greater than(-gt) 5) Print the result.

Program:
#!bin/bash echo "Enter the 3 elements one by one:" read a read b read c if [ $a -gt $b -a $a -gt $c ] then echo "$a is greater" elif [ $b -gt $c ] then echo "$b is greater" else echo "$c is greater" fi

Output:
Enter the 3 elements one by one: 10 20 100 100 is greater

Result:
Thus the program to find the greatest of the given number was executed successfully

OperatingSystem

30

Ex:No:7(b)

Find out the max and min number of a given series

Aim:
Write a program to find out the maximum and minimum number of the given series.

Procedure:
1) Create a new vi editor file. 2) Get the number of elements in the array. 3) Get the elements one by one. 4) Check the numbers one by one 5) Find the maximum and minimum in the given array. 6) Print the result.

Program:
#!bin/bash echo "Enter the no of elements in the array:" read n echo "Enter the elements one by one:" i=0 while [ $i -lt $n ] do read array[$i] let i++ done len=${#array[*]} echo "The array has $len members They are" i=0 while [ $i -lt $len ] do echo "$i:${array[$i]}" let i++ done i=0 j=1 min=${array[$i]} max=${array[$i]} while [ $j -lt $len ]

OperatingSystem

31


do sec=${array[$j]} if [ $min -gt $sec ] then min=$sec elif [ $max -lt $sec ] then max=$sec fi let j++ done echo "Minimum=$min" echo "Maximum=$max"

Output:
[su@localhost pgm]$ bash maxmin Enter the no of elements in the array: 6 Enter the elements one by one: 4 78 3 56 789 45 The array has 6 members they are 0:4 1:78 2:3 3:56 4:789 5:45 Minimum=3 Maximum=789

Result:
Thus the above program to find the maximum and minimum in the given series was executed successfully.

OperatingSystem

32

Viva Questions
1. What is the purpose of shell scripts?
The shell is an intermediary program, which interprets the commands that are typed at the command prompt. The shell translates the commands that you type into commands that are understood by the kernel. The shell acts as an interface between the users and the kernel and eliminates the need for a programmer to communicate directly with the kernal.

2. What are the steps for shell script process.


i) When ou log on, the shell displays the Linux Prompt, indicating that it is ready to execute commands. ii) When you give a command, the shell performs the follwoing tasks. a) Reads the command b) Searches for and locates the file,which has the same name as the command, in the directories containing utilities. c) Loads the appropriate utility into memory. d) Executes the utility.

3. What are the commands are available to execute the script file.
i) At the command prompt ,type $ bash <File Name> If there is an eror in the first line of the shell script that you are executing, you might receive the No such file or directoryerror message. To resolve the problem type the where is bash command to locate the path of the bash program, and use the path in the shell scirpt. ii) At the command prompt ,type $ chmod u+x <File Name> $ ./<File Name>

OperatingSystem

33

Ex.No:8(a)
Aim:

Palindrome Checking

Write a program to convert the lowercase characters into uppercase and uppercase characters into lowercase character of a given string.

Procedure:
1) Create a new vi editor file. 2) Read the input string. 3) Find the length of the given string. 4) Separate the string character by character using substring function. 5) Reverse the string and store the string temporarily 6) compare the reversed string with input string. 7) If it is equal then print the given string is palindrome otherwise print not palindrome

Program:
#!bin/bash echo "Enter the string:" read str len=${#str} k=$len-1 i=0 flag=1 while [ $i -le $((len / 2)) do s1=${str:$i:1} s2=${str:$k-i:1} if [ $s1 != $s2 ] then flag=0 fi let i++ done if [ $flag -eq 1 ] then echo "Palindrome"

OperatingSystem

34


else echo "Not Palindrome" fi

Output:
Enter the string: AMMA Palindrome

Enter the string: Lecturer Not Palindrome

Result:
Thus the above program to covert the upper case into lower case and vice versa were executed successfully.

OperatingSystem

35

Ex.No:8(b)
Aim:

Find the LENGTH of given string

To find the length of given string.

Procedure:
1) Create a new vi editor file. 2) Read the input string. 3) Find the length and substring of the given string. 4) Initialize the count value (i.e.) count=0. 5) If the substring character is match with any vowels character then increase the count value. 6) Print the count value

Program:
#!bin/bash echo"Enterthestring" readstr len=${#str} echo"$len"

Output:
[Stewaugh@localhostsuja]$bashlength Enterthestring Stewaugh 8

Result:
Thus the above program to find the number of vowels present in a given string was executed successfully.

OperatingSystem

36

Viva Questions
1. List out the Arithmetic test operators.

Option
eq ne gt ge lt le Equalto Noteaualto Greaterthan

Meaning

Greaterthanorequalto Lessthan Lessthanorequalto

OperatingSystem

37

Ex.No:9
Aim:

Develop a Calculator Application

To develop a calculator application.

Procedure:
1) Create a new file. 2) Read the operands. 3) Select any one operation from the list. 4) Perform the operation. 5) Print the result.

Program:
# Implementation of Calculator application #!bin/bash j=1 while [ $j -eq 1 ] do echo "Enter the First Operand;" read f1 echo "Enter the second operand:" read f2 echo "1-> Addition" echo "2-> Subtraction" echo "3-> Multiplication" echo "4-> Division" echo "Enter your choice" read n case "$n" in 1) echo "Addition" f3=$((f1+f2)) echo "The result is:$f3" ;; 2) echo "Subtraction" let "f4=$f1 - $f2" echo "The result is:$f4" ;; 3)

OperatingSystem

38


echo "Multiplication" let "f5=$f1 * $f2" echo "The result is:$f5" ;; 4) echo "Division" let "f6=$f1 / $f2" echo "The result is:$f6" ;; esac echo "Do you want to continue(press:1 otherwise press any key to quit)" read j done

Output:
[su@localhost su]$ bash u Enter the First Operand; 23 Enter the second operand: 23 1-> Addition 2-> Subtraction 3-> Multiplication 4-> Division Enter your choice 1 Addition The result is:46 Do you want to continue(press:1 otherwise press any key to quit) 1 Enter the First Operand; 20 Enter the second operand: 2 1-> Addition 2-> Subtraction 3-> Multiplication 4-> Division

OperatingSystem

39


Enter your choice 2 Subtraction The result is:18 Do you want to continue(press:1 otherwise press any key to quit) 1 Enter the First Operand; 24 Enter the second operand: 2 1-> Addition 2-> Subtraction 3-> Multiplication 4-> Division Enter your choice 3 Multiplication The result is:48 Do you want to continue(press:1 otherwise press any key to quit) 1 Enter the First Operand; 24 Enter the second operand: 12 1-> Addition 2-> Subtraction 3-> Multiplication 4-> Division Enter your choice 4 Division The result is:2 Do you want to continue(press:1 otherwise press any key to quit) q [su@localhost su]$

Result:
Thus the above program to develop a calculator application was executed successfully.

OperatingSystem

40

Viva Questions
1. Define a loop.
A loop is a block of code that repeats a set of commands based on the value of the specified condition.

2. Synatx for Looping Statements. While:


While <condition> do <command(s)> done

until:
While <condition> do <command(s)> done

for:
for variable_name in <list_of_values> do <command(s)> done

OperatingSystem

41

C- PROGRAMS
Ex.No:10 Implement Deadlock Avoidance Algorithm using C Language
Aim:
To implement deadlock avoidance algorithm using c language.

Procedure:
1) Create a new file with .c extension. 2) Get the total number of processess, total number of resources and requesting processes. 3) Check whether the requested resources available or not. safe state. 5) Else the particular process is not secure. 4) If it is available then allocate the resources and it consider as a

Program:
#include<stdio.h> #include<stdlib.h> main() { const int max = 10; //max multiplicity int i, j, z; //counters int P, L, N; //P=processes, L= FREE, N= maximum multiplity int A[10], R[10], M[10]; //A= allocates, R=request, M= maximum requests int RS[10]; //RS= folowing request int LS[10]; //free resurces after the i-allocation int CP[10]={0}; //CP= processes classification int MAX[10]; int lim; //max limit do { printf("\nHOW MANY PROCESSES DO YOU WANT? "); scanf("%d",&P); } while(P>max); printf("\nENTER THE TOTAL NO OF RESOURCES: "); scanf("%d",&N);

OperatingSystem

42


for(i=1;i<=P;i++) { printf("\nHOW MANY UNIT HAS THE P%d PROCESS?",i); scanf("%d",&A[i]); printf("\nHOW MANY UNIT REQUEST THE P%d PROCESS?",i); scanf("%d",&R[i]); printf("\nWHAT IS THE MAX NUMBER OF UNITS OF THE P%d PROCESS?",i); scanf("%d",&M[i]); printf("\n\n"); } L=N; for(i=1; i<=P; i++) L-=A[i]; //nuber of units still idle for(i=1; i<=P; i++) { if(R[i]<=L) //is secure? { RS[i]=M[i]-A[i]-R[i]; //next request LS[i]=L-R[i]; //idle resuorces after the allocation } else //isn't secure { LS[i]=-1; } } for(i=1; i<=P; i++) MAX[i]=-1; //or 0??? z=1; for(i=1; i<=P; i++) { if(i==1) { for(j=1; j<=P; j++) { if(LS[j]>=MAX[z]) {

OperatingSystem

43


MAX[z]=LS[j]; CP[z]=j; lim=MAX[z]; } } } else { for(j=1; j<=P; j++) { if((LS[j]>=MAX[z])&&(LS[j]<lim)) { MAX[z]=LS[j]; CP[z]=j; lim=MAX[z]; } } } z++; } for(i=1; i<=P; i++) { if(LS[i]!=-1) printf("\nTHE PROCESS %d IS THE %dstCHOICE\n",i,CP[i]); else printf("THE PROCESS %d IS NOT SECURE",i); } }

Output:
[su@localhost su]$ cc deadlockavoidance.c [su@localhost su]$ ./a.out HOW MANY PROCESSES DO YOU WANT? 2 ENTER THE TOTAL NO OF RESOURCES: 10 HOW MANY UNIT HAS THE P1 PROCESS?3 HOW MANY UNIT REQUEST THE P1 PROCESS?2 WHAT IS THE MAX NUMBER OF UNITS OF THE P1 PROCESS?6

OperatingSystem

44


HOW MANY UNIT HAS THE P2 PROCESS?4 HOW MANY UNIT REQUEST THE P2 PROCESS?7 WHAT IS THE MAX NUMBER OF UNITS OF THE P2 PROCESS?8 THE PROCESS 1 IS THE 1stCHOICE THE PROCESS 2 IS NOT SECURE [su@localhost su]$

Result:
Thus the above C program to implement the deadlock avoidance was executed successfully.

Viva Questions:

1. Define deadlock?
In a multiprogramming environment, several processes may compete for a finite number of resources. A process request resources; if the resources are not available at that time, the process enters a wait state. Waiting processes may never again change state because the resources they have requested are held by other waiting processess.This situation is called deadlock.

(Or)
Two processes would stay blocked forever and no more work would ever be done. This situation is called deadlock.

2. What are the algorithms are available to implement the Deadlock avoidance?
a) Safe state Algorithm. b) Resource Allocation Graph algorithm. c) Bankers algorithm. i) Safety algorithm. ii) Resource-Request Algorithm.

OperatingSystem

45

Ex.No:11
Aim:

Implement Multithreading Concepts


To implement multithreading concept using C language.

Procedure:
1. Create a new file with .c extension. 2. Define the three threads. 3. Each thread is responsible for separate process. All the three threads workout simultaneously. 4. Display the output. 5. Stop the program.

Program:
#include <pthread.h> #include <stdio.h> #define NUM_THREADS 3 void *BusyWork(void *null) { int i; double result=0.0; for (i=0; i<1000000; i++) { result = result + (double)random(); } printf("result = %e\n",result); pthread_exit ((void *) 0); } int main (int argc, char *argv[]) { pthread_t thread[NUM_THREADS]; pthread_attr_t attr; int rc, t; void *status; /* Initialize and set thread detached attribute */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);

OperatingSystem

46


for(t=0; t<NUM_THREADS; t++) { printf("Creating thread %d\n", t); rc = pthread_create(&thread[t], &attr, BusyWork, NULL); if (rc) { printf("ERROR; return code from thread_create()is %d\n", rc); exit(-1); } } /* Free attribute and wait for the other threads */ pthread_attr_destroy(&attr); for(t=0; t<NUM_THREADS; t++) { rc = pthread_join(thread[t], &status); if (rc) { printf("ERROR; return code from pthread_join()is %d\n", rc); exit(-1); } printf("Completed join with thread %d status= %ld\n",t,(long)status); } pthread_exit(NULL); }

Output:
[su@localhost su]$ cc -pthread example2.c [su@localhost su]$ ./a.out Creating thread 0 Creating thread 1 Creating thread 2 result = 1.073708e+15 Completed join with thread 0 status= 0 result = 1.073647e+15 Completed join with thread 1 status= 0

OperatingSystem

47


result = 1.073621e+15 Completed join with thread 2 status= 0 [su@localhost su]$

Result:
Thus the above program to implement the multithreading concept was executed successfully.

Viva Questions:

1. What is meant by thread?


Thread represents a software approach to improve the performance of operating system by reducing the overhead of process switching. It is a light weight process with a reduced state. State reduction is achieved by having a group of related threads share other resources such as memory and files.

2. What is the use of pthread.h header file?


Pthread.h header file must include implementing threading concepts.

3. What is meant by multithreading?


Multiple threads of execution within a single process are called multithreading.

4. List out the benefits of thread compare to the processes


a) Less time to create a new thread than a process, because the newly created thread uses the current process address space. b) Less time to terminate a thread than a process. c) Less time to switch between two threads within the same process, partly because the newly created thread uses the current process address space. d) Less communication overheads -- communicating between the threads of one process is simple because the threads share everything: address space, in particular. So, data produced by one thread is immediately available to all the other threads.

OperatingSystem

48

Ex.No:12
Aim:

First Come First Served (FCFS) Scheduling

To implement FCFS scheduling algorithm and print the average waiting time and average turnaround time.

Procedure:
1. Create a new file with .c extension. 2. Get the number of process, process name, burst time and arrival time of every process. 3. The Gantt chart value is calculated. 4. Calculate average waiting time and average turnaround time. 5. Stop the program.

Program:
#include<stdio.h> #include<string.h> int main() { Int n,i,j,temp,exe[15],arrival[15],wait[15],tat[15], timearray[15]; float twt=0,ttat=0,avgwt=0,avgtat=0; char pid[15][15],tname[15],namearray[15][15]; printf("\n Enter the number of process:"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("\nEnter the process name:"); scanf("%s",&pid[i]); printf("\nEnter the execution time:"); scanf("%d",&exe[i]); printf("\n Enter the arrival time:"); scanf("%d",&arrival[i]); } for(i=1;i<=n;i++) { for(j=i;j<=n;j++) { if(arrival[i]>arrival[j]) {

OperatingSystem

49


strcpy(tname,pid[i]); strcpy(pid[i],pid[j]); strcpy(pid[j],tname); temp=exe[i]; exe[i]=exe[j]; exe[j]=temp; temp=arrival[i]; arrival[i]=arrival[j]; arrival[j]=temp; } } } timearray[0]=0; for(i=1,j=1;i<=n;i++,j++) { if(arrival[i]>timearray[j-1]) { timearray[j]=arrival[i]; strcpy(namearray[j],"idle"); i=i-1; } else { timearray[j]=timearray[j-1]+exe[i]; strcpy(namearray[j],pid[i]); } } for(i=1,j=1;i<=n;i++,j++) { if(strcmp(namearray[j],"idle")==0) { i=i-1; } else { wait[i]=timearray[j-1]-arrival[i]; tat[i]=timearray[j]-arrival[i]; twt=twt+wait[i];

OperatingSystem

50


ttat=ttat+tat[i]; } } avgwt=twt/n; avgtat=ttat/n; printf("\n Name arrival Execution Waiting Turnaround Time\n"); for(i=1,j=1;i<=n;i++,j++) { if(strcmp(namearray[j],"idle")==0) { i=i-1; } else { printf("\n%s",namearray[j]); printf("\t%d",arrival[i]); printf(" 1],timearray[j]); printf(" printf(" printf("\n"); } } printf("\n Average waiting time:%f",avgwt); printf("\n Average turnaround time:%f\n",avgtat); return(0); } %d",wait[i]); %d",tat[i]); %d to %d",timearray[j-

Output:
[su@localhost pgm]$ cc fifc.c [su@localhost pgm]$ ./a.out Enter the number of process:3 Enter the process name:a Enter the execution time:5

OperatingSystem

51


Enter the arrival time:1 Enter the process name:b Enter the execution time:6 Enter the arrival time:3 Enter the process name:c Enter the execution time:7 Enter the arrival time:4 Name a b c arrival 1 3 4 Execution 1 to 6 6 to 12 12 to 19 Waiting 0 3 8 Turnaround Time 5 9 15

Average waiting time:3.666667 Average turnaround time:9.666667 [su@localhost pgm]$

Result:
Thus the above program to implement FCFS Scheduling Algorithm was executed successfully.

Viva Questions: 1. What is meant by First Come First Served?


First-Come-First-Served algorithm is the simplest scheduling algorithm. Processes are dispatched according to their arrival time on the ready queue. Being a no preemptive discipline, once a process has a CPU, it runs to completion.

OperatingSystem

52

EXTRA PROGRAMS
1. Find whether a given number is Prime or not Aim:
Write a program to find whether a given number is prime number or not.

Procedure:
1) Create a new vi editor file. 2) Get the input number. 3) Initially set flag=0 4) Divide the given number by 2. 5) Find the modulo of the dividing output. 6) If the modulo output is zero then set the flag=1. 7) If the flag value is 1 then the given number is a prime number
otherwise the number is not a prime number.

8) Print the result.

Program:
#!bin/bash echo "Enter the number" read n j=2 flag=0 ((y=$n / 2)) while [ $j -le $y ] do ((s=$n % $j )) if [ $s -eq 0 ] then flag=1 fi ((j=$j+1)) done if [ $flag -eq 0 ] then echo "$n is a prime number" else echo "$n is not a prime number" fi

OperatingSystem

53

Output:
[su@localhost su]$ bash prime Enter the number 123 123 is not a prime number [su@localhost su]$ bash prime Enter the number 11 11 is a prime number [su@localhost su]$

OperatingSystem

54

2. String Conversion
Aim:
Write a program to convert the lowercase characters into uppercase and uppercase characters into lowercase character of a given string.

Procedure:
1) Create a new vi editor file. 2) Read the input string. 3) Find the length of the given string. 4) Separate the string character by character using substring function. 5) Check whether the character is upper or lower. 6) If the character is upper covert to lower case character otherwise converted into uppercase. 7) Print the converted string.

Program:
#!bin/bash echo "Enter the string" read str array=(a b c d e f g h i j k l m n o p q r s t u v w x y z) a1=${#array[*]} arr=(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) a2=${#arr} st=${#str} echo "The string length is:$st" i=0 j=1 k=0 f=0 while [ $k -lt $st ] do ss=${str:$i:$j} while [ $f -lt $a1 ] do if [ $ss = ${array[$f]} ] then str=${str/$ss/${arr[$f]}} elif [ $ss = ${arr[$f]} ] then

OperatingSystem

55


str=${str/$ss/${array[$f]}} fi let f++ done f=0 let k++ let i++ done echo "$str"

Output:
[su@localhost pgm]$ bash upperlower Enter the string ComPutErSciENcE The string length is:15 COMpUTeRsCIence [su@localhost pgm]$

Result:
Thus the above program to covert the upper case into lower case and vice versa were executed successfully.

OperatingSystem

56

3. Find the number of vowels in a given string

Aim: To find the vowels in a string Procedure:


7) Create a new vi editor file. 8) Read the input string. 9) Find the length and substring of the given string. 10) Initialize the count value (i.e.) count=0. 11) If the substring character is match with any vowels character then increase the count value. 12) Print the count value

Program:
#!bin/bash echo "Enter the string" read str k=${#str} echo "The string Length is:$k" i=0 d=1 j=0 count=0 while [ $j -lt $k ] do g=${str:$i:$d} if [ $g = a -o $g = e -o $g = i -o $g = o -o $g = u -o $g = A -o $g = E -o $g =I -o $g = O -o $g = U ] then let count++ fi let i++ let j++ done echo "Number of vowels in the given string is:$count"

OperatingSystem

57

Output:
[su@localhost su]$ bash vowels Enter the string Kanyakumari The string Length is:11 Number of vowels in the given string is:5

Result:
Thus the above program to find the number of vowels present in a given string was executed successfully.

OperatingSystem

58

También podría gustarte