Weebly
[pic]
Departments of
Computer Science & Engineering
&
Information Technology
OPERATING SYSTEM LAB
LABORATORY MANUAL
Common to CSE, IT
Prepared by
M . ARUNA - LECTURER / CSE
J . GHAYATHRI - LECTURER / CSE
ACADEMIC YEAR 2009 - 2010 (EVEN SEMESTER)
CS2257 OPERATING SYSTEMS LAB
(Common to CSE & IT)
(Implement the following on LINUX or other Unix like platform. Use C for high level language implementation)
1. Write programs using the following system calls of UNIX operating system:
fork, exec, getpid, exit, wait, close, stat, opendir, readdir
2. Write programs using the I/O system calls of UNIX operating system (open, read,
write, etc)
3. Write C programs to simulate UNIX commands like ls, grep, etc.
4. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt chart for FCFS and SJF. For each of the scheduling policies, compute and print the average waiting time and average turnaround time. (2 sessions)
5. Given the list of processes, their CPU burst times and arrival times, display/print the Gantt chart for Priority and Round robin. For each of the scheduling policies, compute and print the average waiting time and average turnaround time. (2 sessions)
6. Developing Application using Inter Process communication (using shared memory, pipes or message queues)
7. Implement the Producer – Consumer problem using semaphores (using UNIX system calls).
8. Implement some memory management schemes – I
9. Implement some memory management schemes – II
10. Implement any file allocation technique (Linked, Indexed or Contiguous)
Example for exercises 8 & 9 :
Free space is maintained as a linked list of nodes with each node having the starting byte address and the ending byte address of a free block. Each memory request consists of the process-id and the amount of storage space required in bytes. Allocated memory space is again maintained as a linked list of nodes with each node having the process-id, starting byte address and the ending byte address of the allocated space. When a process finishes (taken as input) the appropriate node from the allocated list
Should be deleted and this free disk space should be added to the free space list. [Care should be taken to merge contiguous free blocks into one single block. This results in deleting more than one node from the free space list and changing the start and end address in the appropriate node]. For allocation use first fit, worst fit and best fit.
THE UNIX OPERATING SYSTEM
Operating System:
An Operating System is a program that manages the computer hardware and acts as an interface between the user and the computer system. It provides working environment where the users run their applications.
The UNIX OS:
The UNIX operating system originated from AT&T (now USL) in the early 1970's. Because UNIX was able to run on different hardware from different vendors, this encouraged developers to modify UNIX and distribute it as their own value-added version of UNIX. Separate UNIX traditions evolved as a result: USL's System V, Berkeley Standard Distribution (BSD, from the University of California, Berkeley), Xenix, etc.
In recent years, the UNIX operating system has seen a huge boost in its popularity, especially with the emergence of Linux. For programmers and users of UNIX, this comes as no surprise. UNIX was designed to provide an environment that's powerful yet easy to use.
One of the main strengths of UNIX is that it comes with a large collection of standard programs. These programs perform a wide variety of tasks from listing your files to reading email. Unlike other operating systems, one of the key features of UNIX is that these programs can be combined to perform complicated tasks and solve your problems.
One of the most powerful standard programs available in UNIX is the shell. The shell is a program that provides a consistent and easy-to-use environment for executing programs in UNIX. The main responsibility of the shell is to read the commands the user types and then ask the UNIX kernel to perform these commands. In addition to this, the shell provides sophisticated programming constructs that enable us to make decisions, repeatedly execute commands, create functions, and store values in variables.
Features:
• Unix is a multi user operating system which allows several users to share the system resources.
• It is a multi processing Operating System which performs several tasks simultaneously.
• It is a time sharing operating system where the processes interactively share the CPU time.
• It has a portability feature which allows it to be implemented on any platform without any major alterations.
Structure:
The fig Shows the basic structure of the UNIX operating system.
The Application Layer:
The application layer is the one with which the user interacts .The application layer comprises of various software components which implement the requirements of the user and provide the user with a working environment.
Shell:
The shell acts as an arbitrary protection to the Kernel. It interprets the user commands and converts it to a form which the kernel understands. It acts as a command interpreter. It acts as an interface between the application and the kernel.
Kernel:
It is said to be the core of the UNIX operating system. It is a program which is loaded to the memory when the system starts up and keeps running until the system is shutdown.
Firmware:
A Firmware is one which controls the hardware of the computer system. It acts as an interface between the Kernel and the hardware. The Kernel passes the requests of the user to the firmware of the system which is responsible for executing the requested operations with the hardware.
Hardware :
The hardware comprises of the Input / Output devices and the Central Processing Unit CPU, which actually performs the requested operations.
The UNIX Directory structure:
UNIX COMMANDS
Communication
|Cu |Connect to UNIX system. |
|ftp |File transfer protocol. |
|login |Sign on to UNIX. |
|mailx |Read or send mail. |
|rlogin |Sign on to remote UNIX. |
|talk |Write to other terminals. |
|telnet |Connect to another system. |
|vacation |Respond to mail automatically. |
|write |Write to other terminals. |
File Management
|cat |Join files or display them. |
|cd |Change directory. |
|chmod |Change access modes on files. |
|cp |Copy files. |
|csplit |Break files at specific locations. |
|file |Determine a file's type. |
|head |Show the first few lines of a file. |
|install |Set up system files. |
|ln |Create filename aliases. |
|ls |List files or directories. |
|mkdir |Create a directory. |
|more |Display files by screenful. |
|mv |Move or rename files or directories. |
|pwd |Print your working directory. |
|rcp |Copy files to remote system. |
|rm |Remove files. |
|rmdir |Remove directories. |
|split |Split files evenly. |
|tail |Show the last few lines of a file. |
|wc |Count lines, words, and characters. |
1
2 Miscellaneous
|banner |Make posters from words. |
|bc |Precision calculator. |
|cal |Display calendar. |
|calendar |Check for reminders. |
|clear |Clear the screen. |
|kill |Terminate a running command. |
|man |Get information on a command. |
|nice |Reduce a job's priority. |
|nohup |Preserve a job after logging out. |
|passwd |Set password. |
|script |Produce a transcript of your login session. |
|spell |Report misspelled words. |
|su |Become a superuser. |
Printing
|cancel |Cancel a printer request. |
|lp |Send to the printer. |
|lpstat |Get printer status. |
|pr |Format and paginate for printing. |
Programming
|cb |C source code "beautifier." |
|cc |C compiler. |
|cflow |C function flowchart. |
|ctags |C function references. |
|ctrace |C debugger. |
|cxref |C cross-references. |
|lint |C debugger. |
|ld |Link editor. |
|lex |Lexical analyzer. |
|make |Execute commands in a specified Order. |
|od |Dump input in various formats. |
|sdb |Symbolic debugger. |
|strip |Remove data from an object file. |
|truss |Trace signals and system calls. |
|yacc |Compiler used with lex. |
Searching
|egrep |Extended version of grep. |
|fgrep |Search files for literal words. |
|find |Search the system for filenames. |
|grep |Search files for text patterns. |
|strings |Search binary files for text patterns. |
Shell Programming
|echo |Repeat input on the output. |
|expr |Perform arithmetic and comparisons. |
|line |Read a line of input. |
|sleep |Pause during processing. |
|test | Test a condition. |
System Status
|at |Execute commands later. |
|chgrp |Change file group. |
|chown |Change file owner. |
|crontab |Automate commands. |
|date |Display or set date. |
|df |Show free disk space. |
|du |Show disk usage. |
|env |Show environment variables. |
|finger |Point out information about users. |
|ps |Show processes. |
|ruptime |Show loads on working systems. |
|shutdown |Revert to single-user mode. |
|stty |Set or display terminal settings. |
|who |Show who is logged on. |
UNIX COMMANDS
• touch
This command is used to change the time stamp of a file.
Syntax:
$ touch
The file name specified can be any file irrespective of if it exists or not .If the file already exists it changes just the time stamp ,a new file is created otherwise .
• who
This command displays the current users logged in .
Syntax:
$who
[[student@localhost ~]$ who
student tty7 2009-12-10 13:25 (:0)
student pts/1 2009-12-10 13:28 (:0.0)
• date
This command displays the current system date.
Options:
❖ +%D displays it in the form mm/dd/yyyy
❖ +%H displays the current hour 0-23
❖ +%M hh: mm: ss
[CSE@localhost ~]$ date
Thu Dec 10 14:17:37 IST 2009
[CSE@localhost ~]$ date +%D
12/10/09
[CSE@localhost ~]$ date +%H
14
[CSE@localhost ~]$ date +%M
33
[CSE@localhost ~]$ date +%S
36
• ls
It is used to list the contents of a directory.
Syntax:
$ ls [-options]
Options:
a – to list all directory entries including hidden files (files with a ‘.’ prefix)
d – to list directories
l – to long list files .
r – to list files in reverse order
t – to list files sorted by time
f – mark executable file with * and directories with %
l – one file per line
$ ls –l
This command displays the content of the current directory in long terms.
drwxr-xr-x 2 CSE CSE 4096 2009-11-29 11:46 Desktop
drwxr-xr-x 2 CSE CSE 4096 2009-11-29 11:46 Documents
drwxr-xr-x 2 CSE CSE 4096 2009-11-29 11:46 Download
-rw-rw-r-- 1 CSE CSE 1064 2009-11-30 14:00 in.c
• cat
It is used to create a file.
Syntax:
cat > filename
$cat >oslab
LINUX COMMANDS
CAT
To come out of this command press ctrl+D. The characters in each line should not exceed 14 characters. The same command is also use to display the contents of a file.
The syntax is
cat
$cat oslab
LINUX COMMANDS
CAT
• mkdir
This command is used to create a directory in the current working directory.
Syntax :
mkdir
[CSE@localhost ~]$ mkdir CSE
[CSE@localhost ~]$ ls
a.out Desktop Download Music Pictures Templates
CSE Documents in.c oslab Public Videos
[CSE@localhost ~]$ ls -ld CSE
drwxrwxr-x 2 CSE CSE 4096 2009-12-10 13:44 CSE
• cd
This command is used to change the working directory to the specified directory.
Syntax:
cd
[CSE@localhost ~]$ cd CSE
[CSE@localhost CSE]$ pwd
/home/CSE/CSE
• pwd
This command is used to display the current working directory.
Syntax:
pwd
$pwd
/home/CSE/CSE
• rmdir
This command is used to remove a directory from current working directory.
Syntax:
rmdir
[CSE@localhost ~]$ rmdir CSE
[CSE@localhost ~]$ ls -ld CSE
ls: cannot access CSE: No such file or directory
• cp
This command is used to create a duplicate copy of file.
Syntax:
cp
$cp srcfile destfile
[CSE@localhost ~]$ cp oslab os
[CSE@localhost ~]$ cat os
LINUX COMMANDS
CAT
• mv
This command is used to change the name of file.
Syntax:
mv
[CSE@localhost ~]$ mv os oslab1
[CSE@localhost ~]$ ls os
ls: cannot access os: No such file or directory
• rm
This command is used to delete a file.
Syntax:
rm -[options]
Options:
❖ i – interactive deleting (ie confirm before deleting file)
❖ f – deleting files without confirmation.
❖ r – delete all directories including sub directories.(recursive deleting).
[CSE@localhost ~]$ rm -i oslab1
rm: remove regular file `oslab1'? y
[CSE@localhost ~]$ cat oslab1
cat: oslab1: No such file or directory
• more
This command is used to display the information page wise.
Syntax:
more
[CSE@localhost ~]$ more oslab1
LINUX COMMANDS
CAT
[CSE@localhost ~]$ more /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
• wc
This command is used to count the number of lines, words and characters in a file.
Syntax:
wc -[options]
Options:
❖ i — to count the number of files
❖ c — to count the number of characters
❖ w — to count the number of words
[[CSE@localhost ~]$ cat >oslab3
shell
[CSE@localhost ~]$ wc -c oslab3
6 oslab3
[CSE@localhost ~]$ wc -w oslab3
1 oslab3
• cmp
This is used to compare two files.
Syntax:
cmp file1 file2
This reports the first difference between the files. Does not report if the two files are same.
$cmp oslab oslab1
oslab oslab1 differ: byte 1, line 1
• lp
This command is used to print a file.
Syntax:
lp
$ lp test
• >
This operator is used to redirect an output to a file .
Syntax:
cat (file name) > (file name)
[CSE@localhost ~]$ cat oslab1
unix
shell pgmming
[CSE@localhost ~]$ cat oslab2
shell
[CSE@localhost ~]$ cat oslab1 > oslab2
[CSE@localhost ~]$ cat oslab2
unix
shell pgmming
This command redirects the content of the first file to the second file .The operator can also be used with other commands to redirect their output to a file. A new file is created if it does not exist. The contents of the file is deleted if the file exists.
[CSE@localhost ~]$ date
Thu Dec 10 14:17:37 IST 2009
[CSE@localhost ~]$ date > date1.txt
[CSE@localhost ~]$ cat date1.txt
Thu Dec 10 14:18:07 IST 2009
• >>
This operator is used to append the text to the destination file specified.
Syntax :
cat (file name) >> (file name)
This command is used to redirect the output of a command to a file .In this case the output is appended to the destination file rather than deleting the contents ie., the new contents is added at the end of the file.
[CSE@localhost ~]$ cat oslab2
unix
shell pgmming
[CSE@localhost ~]$ cat oslab3
shell
[CSE@localhost ~]$ cat oslab2 >> oslab3
[CSE@localhost ~]$ cat oslab3
shell
unix
shell pgmming
• echo
echo is used to display the string of characters after the command on the screen.
[CSE@localhost ~]$ echo scheduling policies
scheduling policies
• grep
This command is used to search for a particular string in a file.
Syntax :
grep
It displays the lines in the file containing the text “root”
[CSE@localhost ~]$ grep shell oslab3
shell
shell pgmming
• sort
This command is used for sorting a specific contents in a particular order.
[CSE@localhost ~]$ cat >sorting
3
5
7
1
2
4
6
[CSE@localhost ~]$ sort -g sorting
1
2
3
4
5
6
7
This sorts the numbers in the file 'sorting' in ascending order.
• tail
This command is used to display the last few lines of a file as it’s argument.
$ tail file1
displays the last few lines of the file file1
[CSE@localhost ~]$ tail /etc/passwd
EEE:x:501:501::/home/EEE:/bin/bash
ECE:x:502:502::/home/ECE:/bin/bash
CSE:x:503:503::/home/CSE:/bin/bash
IT:x:504:504::/home/IT:/bin/bash
OWNERS, GROUPS, AND PERMISSIONS
File ownership is an important component of UNIX that provides a secure method for storing files. Every file in UNIX has the following attributes:
• Owner permissions
• Group permissions
• Other (world) permissions
• The owner's permissions determine what actions the owner of the file can perform on the file.
• The group's permissions determine what actions a user, who is a member of the group that a file belongs to, can perform on the file.
• The permissions for others indicate what action all other users can perform on the file.
The following actions can be performed on a file:
• Read
• Write
• Execute
If a user has read permissions, that person can view the contents of a file. A user with write permissions can change the contents of a file, whereas a user with execute permissions can run a file as a program.
Viewing Permissions
You can display the permissions of a file using the ls -l command. For example, the following command
$ ls -l /home/ranga/.profile
produces the following output:
-rwxr-xr-x 1 ranga users 2368 Jul 11 15:57 .profile*
The first three characters after the ‘-‘ indicate the permissions for the owner of the file, the next three characters indicate the permissions for the group the file is associated with, and the last three characters indicate the permissions for all other users.
The permission block for this file indicates that the user has read, write, and execute permissions, whereas
members of the group users and all other users have only read and execute permissions.
Three basic permissions that can be granted or denied on a file are read, write, and execute. These permissions are defined in the table
After the permissions block, the owner and the group are listed. For this file, the owner is ranga and the group is users.
Basic Permissions
Letter Permission Definition
r Read The user can view the contents of the file.
w Write The user can alter the contents of the file.
x Execute The user can run the file, which is likely a program. For directories, the execute permission must be set in order for users to access the directory.
Directory Permissions
The x bit on a directory grants access to the directory. The read and write permissions have no effect if the access bit is not set. The read permission on a directory enables users to use the ls command to view files and their attributes that are located in the directory. The write permission on a directory is the permission to watch out for because it lets a user add and also remove files from the directory.
A directory that grants a user only execute permission will not enable the user to view the contents of the directory or add or delete any files from the directory, but it will let the user run executable files located in the directory.
SUID and SGID File Permission
Often when a command is executed, it will have to be executed with special privileges in order to accomplish its task.
As an example, when you change your password with the passwd command, your new password is stored in the file /etc/shadow. As a regular user, you do not have read or write access to this file for security reasons, but when you change your password, you need to have write permission to this file. This means that the passwd program has to give you additional permissions so that you can write to the file /etc/shadow.
Additional permissions are given to programs via a mechanism known as the Set User ID ( SUID) and Set Group ID ( SGID) bits. When you execute a program that has the SUID bit enabled, you inherit the permissions of that program's owner. Programs that do not have the SUID bit set are run with the permissions of the user who started the program. This is true for SGID as well. Normally programs execute with your group permissions, but instead your group will be changed just for this program to the group owner of the program. As an example, the passwd command, used to change your password, is owned by the root and has the set SUID bit enabled. When you execute it, you effectively become root while the command runs.
The SUID and SGID bits will appear as the letter "s" if the permission is available. The SUID "s" bit will be located in the permission bits where the owners execute permission would normally reside. For example, the command
$ ls -l /usr/bin/passwd
produces the following output:
-r-sr-xr-x 1 root bin 19031 Feb 7 13:47 /usr/bin/passwd*
which shows that the SUID bit is set and that the command is owned by the root. A capital letter S in the execute position instead of a lowercase s indicates that the execute bit is not set. The SUID bit or stick bit imposes extra file removal permissions on a directory. A directory with write permissions enabled for a user enables that user to add and delete any files from this directory. If the sticky bit is enabled on the directory, files can only be removed if you are one of the following users:
The owner of the sticky directory
The owner the file being removed
The super user, root
Changing File and Directory Permissions
The file and directory permissions can be changed with the chmod command. The basic syntax is as follows:
chmod expression files
Here, expression is a statement of how to change the permissions. This expression can be of
the following types:
Symbolic
Octal
The symbolic expression method uses letters to alter the permissions, and the octal expression method uses numbers. The numbers in the octal method are base-8 (octal) numbers ranging from 0 to 7.
Symbolic Method
The symbolic expression has the syntax of
(who)(action)(permissions)
Letter Represents
u Owner
g Group
o Other
a All
Symbol Represents
+ Adding permissions to the file
- Removing permission from the file
= Explicitly set the file permissions
Letter Represents
r Read
w Write
x Execute
s SUID or SGID
• To give the "world" read access to all files in a directory, you can use one of the following commands:
$ chmod a=r *
or
$ chmod guo=r *
If the command is successful, it produces no output.
• To stop anyone except the owner of the file .profile from writing to it,
$ chmod go-w .profile
• To deny access to the files in your home directory,
$ cd ; chmod go= *
or
$ cd ; chmod go-rwx *
Caution - If you do this, be warned because some users will call you a file miser.
When specifying the users part or the permissions part, the order in which you give the letters is irrelevant.
Thus these commands are equivalent:
$ chmod guo+rx *
$ chmod uog+xr *
If more than one set of permissions changes need to b applied to a file or files, use a comma separated list:
$ chmod go-w,a+x a.out
removes the groups and "world" write permission on a.out and adds the execute permission for everyone.
To set the SUID and SGID bits for your home directory, try the following:
$ cd ; chmod ug+s .
Chmod also enables us to change the permissions for every file in a directory including the files in subdirectories.
This can accomplish this by specifying the -R option.
If the directory pub contains the following directories:
$ ls pub
./ ../ README faqs/ src/
The permissions of the file README along with the files contained in the directories faqs and src can be changed with the following command:
$ chmod -R o+r pub
Octal Method
By changing permissions with an octal expression, we can only explicitly set file permissions. This method uses a single number to assign the desired permission to each of the three categories of users (owner, group, and other).
The values of the individual permissions are the following:
Read permission has a value of 4
Write permission has a value of 2
Execute permission has a value of 1
Adding the value of the permissions that you want to grant will give you a number between 0 and 7. This number will be used to specify the permissions for the owner, group, and finally the other category. Setting SUID and SGID using the octal method places these bits out in front of the standard permissions. The permissions SUID and SGID take on the values 4 and 2, respectively.
In order to set the "world" read access to all files in a directory,
chmod 0444 *
To stop anyone except the owner of the file .profile from writing to it,
chmod 0600 .profile
SHELL PROGRAMMING
A Linux shell is a command language interpreter, the primary purpose of which is to translate the command lines typed at the terminal into system actions. The shell itself is a program, through which other programs are invoked
What is a shell script?
• A shell script is a file containing a list of commands to be executed by the Linux shell. shell script provides the ability to create your own customized Linux commands
• Linux shell have sophisticated programming capabilities which makes shell script powerful Linux tools
Why Use Shells?
Well, most likely because the are a simple way to string together a bunch of UNIX commands for execution at any time without the need for prior compilation. Also because its generally fast to get a script going. Not forgetting the ease with which other scripters can read the code and understand what is happening. Lastly, they are generally completely portable across the whole UNIX world, as long as they have been written to a common standard.
The Shell History:
The basic shells come in three main language forms. These are (in order of creation) sh, csh and ksh. Be aware that there are several dialects of these script languages which tend to make them all slightly platform specific. Where these differences are known to cause difficulties I have made special notes within the text to highlight this fact. The different dialects are due, in the main, to the different UNIX flavours in use on some platforms. All script languages though have at their heart a common core which if used correctly will guarantee portability.
Bourne Shell:
Historically the sh language was the first to be created and goes under the name of The Bourne Shell. It has a very compact syntax which makes it obtuse for novice users but very efficient when used by experts. It also contains some powerful constructs built in. On UNIX systems, most of the scripts used to start and configure the operating system are written in the Bourne shell. It has been around for so long that is it virtually bug free. I have adopted the Bourne shell syntax as the defacto standard within this book.
C Shell:
Next up was The C Shell (csh), so called because of the similar syntactical structures to the C language. The UNIX man pages contain almost twice as much information for the C Shell as the pages for the Bourne shell, leading most users to believe that it is twice as good. This is a shame because there are several compromises within the C Shell which makes using the language for serious work difficult (check the list of bugs at the end of the man pages!). True, there are so many functions available within the C Shell that if one should fail another could be found. The point is do you really want to spend your time finding all the alternative ways of doing the same thing just to keep yourself out of trouble. The real reason why the C Shell is so popular is that it is usually selected as the default login shell for most users. The features that guarantee its continued use in this arena are aliases, and history lists. There are rumours however, that C Shell is destined to be phased out, with future UNIX releases only supporting sh and ksh. Differences between csh and sh syntax will be highlighted where appropriate.
Korne Shell:
Lastly we come to The Korne Shell (ksh) made famous by IBM's AIX flavour of UNIX. The Korne shell can be thought of as a superset of the Bourne shell as it contains the whole of the Bourne shell world within its own syntax rules. The extensions over and above the Bourne shell exceed even the level of functionality available within the C Shell (but without any of the compromises!), making it the obvious language of choice for real scripters. However, because not all platforms are yet supporting the Korne shell it is not fully portable as a scripting language at the time of writing. This may change however by the time this book is published. Korne Shell does contain aliases and history lists aplenty but C Shell users are often put off by its dissimilar syntax. Persevere, it will pay off eventually. Any sh syntax element will work in the ksh without change.
How to work with shell?
Step1:
In the dollar prompt type
$ vi < file name>
Where vi is the editor, it will open a new window in which you can type the program you want
Step2:
After typing the program press ESC and : together then at the bottom of the vi screen you can see i.e. prompt .In that type as wq which means write and quit i.e. the content what is typed will be written and saved into that file that has been created
Step3:
Once wq is typed at the: prompt, the prompt would change to $ symbol in which you have to do the following
$ sh < file name >
Sh - command is used to run the shell program
- is the name of the file for which the output is to be got
Basically to print a text in the your shell programs echo command is used
1 How to Run Shell Scripts
There are two ways you can execute your shell scripts. Once you have created a script file:
Method 1:
Pass the file as an argument to the shell that you want to interpret your script.
Step 1: create the script using vi, ex or ed
For example, the script file show has the following lines
echo Here is the date and time
date
Step 2: To run the script, pass the filename as an argument to the sh (shell)
$ sh show
Here is the date and time
Thu Dec 10 14:18:07 IST 2009
Method 2:
Make your script executable using the chmod command.
When we create a file, by default it is created with read and write permission turned on and execute permission turned off. A file can be made executable using chmod.
Step 1: create the script using vi, ex or ed
For example, the script file show has the following lines
echo Here is the date and time
date
Step 2: Make the file executable
$ chmod u+x script_file
$ chmod u+x show
Step 3: To run the script, just type the filename
$ show
Here is the date and time
Sat jun 03 13:40:15 PST 2006
How to run C programs?
Step 1: Use an editor, such as vi, ex, or ed to write the program. The name of the file containing the program should end in .c.
For example, the file show.c contains the following lines :
main()
{
printf(“ welcome to GNEC “);
}
Step 2: Submit the file to CC ( the C Compiler )
$ cc show.c
If the program is okay, the compiled version is placed in a file called a.out
Step 3: To run the program, type a.out
$ a.out
Welcome to GNEC
MULTIPLICATION TABLE
PROGRAM:
clear
echo Multiplication Table
echo Enter the Number
read a
for b in 1 2 3 4 5 6 7 8 9 10 11 12
do
echo $b $a "'s are" `expr $b "*" $a`
done
OUTPUT:
Multiplication Table
Enter the Number
12
1 12 's are 12
2 12 's are 24
3 12 's are 36
4 12 's are 48
5 12 's are 60
6 12 's are 72
7 12 's are 84
8 12 's are 96
9 12 's are 108
10 12 's are 120
11 12 's are 132
12 12 's are 144
GREETING THE USER
PROGRAM:
clear
echo Program for Greeting the User as per the current system time
n=`date +%H`
if [ $n -lt 12 ]
then
echo " Good Morning "
elif [ $n -ge 12 -a $n -lt 16 ]
then
echo " Good AfterNoon "
elif [ $n -ge 16 -a $n -lt 18 ]
then
echo " Good Evenening "
elif [ $n -ge 18 ]
then
echo " Good Night "
fi
OUTPUT:
Program for Greeting the User as per the current system time
Good AfterNoon
ARITHEMATIC OPERATIONS
PROGRAM:
clear
ch=1
while [ $ch -gt 0 ]
do
echo MENU
echo 1.Addition
echo 2.Subtraction
echo 3.Multiplication
echo 4.Division
echo 5.exit
echo
echo Enter your choice :
read ch
case $ch
in
1) echo Addition of two numbers
echo Enter the first number
read a
echo Enter the second number
read b
echo Result after addition
echo "`expr $a "+" $b`";;
2)echo Subtraction of two numbers
echo Enter the Subtrahend
read c
echo Enter the Minuend
read d
echo Result after subtraction
echo `expr $c "-" $d`;;
3)echo Multiplication of two numbers
echo Enter the first number
read e
echo Enter the second number
read f
echo Result of multiplication
echo `expr $e "*" $f`;;
4)echo Division of two numbers
echo Enter the numerator
read g
echo Enter the Denominator
read h
echo Result of Division
echo `expr $g "/" $h`;;
5)echo Exiting program
ch=0;;
esac
done
OUTPUT:
MENU
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.exit
Enter your choice :
1
Addition of two numbers
Enter the first number
12
Enter the second number
13
Result after addition
25
MENU
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.exit
Enter your choice :
2
Subtraction of two numbers
Enter the Subtrahend
25
Enter the Minuend
12
Result after subtraction
13
MENU
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.exit
Enter your choice :
3
Multiplication of two numbers
Enter the first number
12
Enter the second number
15
Result of multiplicaton
180
MENU
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.exit
Enter your choice :
4
Division of two numbers
Enter the numerator
12
Enter the Denominator
6
Result of Division
2
MENU
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.exit
Enter your choice :
5
Exiting program
DIRECTORY OPERATIONS
PROGRAM:
clear
ch=1
while [ $ch -le 6 ]
do
echo 1.Create Directory
echo 2.Change Directory
echo 3.Present Working Directory
echo 4.Change to Parent Directory
echo 5.Remove Directory
echo 6.List the directory Content
echo 7.Exit
echo Enter ur choice
read ch
case $ch
in
1)echo Enter the name of the directory to create
read crdir
mkdir $crdir;;
2)echo Enter the name of the directory to change to
read chdir
cd $chdir;;
3)echo The Present Working Directory is
pwd;;
4)echo Changing to the parent directory
cd ..;;
5)echo Enter the name of the directory to delete
read deldir
rmdir $deldir;;
6)echo Listing the directory contents
ls -la;;
esac
done
OUTPUT :
1.Create Directory
2.Change Directory
3.Present Working Directory
1.Create Directory
2.Change Directory
3.Present Working Directory
4.Change to Parent Directory
5.Remove Directory
6.List the directory Content
7.Exit
Enter ur choice
1
Enter the name of the directory to create
cse
1.Create Directory
2.Change Directory
3.Present Working Directory
4.Change to Parent Directory
5.Remove Directory
6.List the directory Content
7.Exit
Enter ur choice
2
Enter the name of the directory to change to
cse
1.Create Directory
2.Change Directory
3.Present Working Directory
4.Change to Parent Directory
5.Remove Directory
6.List the directory Content
7.Exit
Enter ur choice
3
The Present Working Directory is
/home/cse64/cse
1.Create Directory
2.Change Directory
3.Present Working Directory
4.Change to Parent Directory
5.Remove Directory
6.List the directory Content
7.Exit
Enter ur choice
4
Changing to the parent directory
1.Create Directory
2.Change Directory
3.Present Working Directory
4.Change to Parent Directory
5.Remove Directory
6.List the directory Content
7.Exit
Enter ur choice
3
The Present Working Directory is
/home/cse64
1.Create Directory
2.Change Directory
3.Present Working Directory
4.Change to Parent Directory
5.Remove Directory
6.List the directory Content
7.Exit
Enter ur choice
2
Enter the name of the directory to change to
cse
1.Create Directory
2.Change Directory
3.Present Working Directory
4.Change to Parent Directory
5.Remove Directory
6.List the directory Content
7.Exit
Enter ur choice
6
Listing the directory contents
total 8
drwxrwxr-x 2 cse64 cse64 4096 Feb 18 15:46 .
drwx------ 5 cse64 cse64 4096 Feb 18 15:46 ..
1.Create Directory
2.Change Directory
3.Present Working Directory
4.Change to Parent Directory
5.Remove Directory
6.List the directory Content
7.Exit
Enter ur choice
4
Changing to the parent directory
1.Create Directory
2.Change Directory
3.Present Working Directory
4.Change to Parent Directory
5.Remove Directory
6.List the directory Content
7.Exit
Enter ur choice
5
Enter the name of the directory to delete
cse
1.Create Directory
2.Change Directory
3.Present Working Directory
4.Change to Parent Directory
5.Remove Directory
6.List the directory Content
7.Exit
Enter ur choice
7
FILE MANIPULATION
PROGRAM:
echo Program for File Management
echo 1.Create
echo 2.Display
echo 3.Modify
echo 4.Delete
echo 5.Copy
echo Enter ur choice
read ch
case $ch
in
1)echo Enter the name of the file to create
read crfile
cat > $crfile;;
2)echo Enter the name of the file to display
read disfile1
cat $disfile1;;
3)echo "Enter the name of the file to Modi"
read modfile
cat>>$modfile;;
4)echo Enter the name of the file name to delete
read delfile
rm $delfile;;
5)echo Enter the name of the source file
read sorfile
echo Enter the name of the destination file
read destifile
cp $sorfile $destifile;;
esac
OUTPUT:
Program for File Management
1.Create
2.Display
3.Modify
4.Delete
5.Copy
Enter ur choice
1
Enter the name of the file to create
test
this is for test
[cse64@localhost cse64]$ sh filem.sh
Program for File Management
1.Create
2.Display
3.Modify
4.Delete
5.Copy
Enter ur choice
2
Enter the name of the file to display
test
this is for test
[cse64@localhost cse64]$ sh filem.sh
Program for File Management
1.Create
2.Display
3.Modify
4.Delete
5.Copy
Enter ur choice
3
Enter the name of the file to Modi
test
This is also for test
[cse64@localhost cse64]$ sh filem.sh
Program for File Management
1.Create
2.Display
3.Modify
4.Delete
5.Copy
Enter ur choice
5
Enter the name of the source file
test
Enter the name of the destination file
test1
Program for File Management
1.Create
2.Display
3.Modify
4.Delete
5.Copy
Enter ur choice
4
Enter the name of the file name to delete
test
FILE PERMISSIONS
PROGRAM :
f=0
echo Enter the name of the file
read file
if test -d $file
then
echo $file is a directory
f=1
exit
fi
if test -f $file
then
echo $file is an Ordinary file
f=1
fi
if test -r $file
then
echo $file is a file with read permission
f=1
fi
if test -w $file
then
echo $file is a file with write permission
f=1
fi
if test -x $file
then
echo $file is a file with execute permissions
f=1
fi
if [ $f -eq 0 ]
then
echo file not found
fi
OUTPUT :
Enter the name of the file
fileop.sh
fileop.sh is an Ordinary file
fileop.sh is a file with read permission
fileop.sh is a file with write permission
fileop.sh is a file with execute permissions
LARGEST OF THREE NUMBERS
PROGRAM :
echo Program to find the largest of three numbers
echo Enter the first number
read num1
echo Enter the second number
read num2
echo Enter the third number
read num3
if [ $num1 -gt $num2 ]
then
if [ $num1 -gt $num3 ]
then
echo the largest number is $num1
else
echo the largest number is $num3
fi
elif [ $num2 -gt $num3 ]
then
echo the largest number is $num2
else
echo the largest number is $num3
fi
OUTPUT:
Program to find the largest of three numbers
Enter the first number
12
Enter the second number
10
Enter the third number
44
the largest number is 44
SORTING
PROGRAM:
clear
echo Sorting the contents of a file
echo Enter the file name
read file
echo Sorted output of $file
echo
echo
sort -g $file
echo
OUTPUT:
Sorting the contents of a file
Enter the file name
sortsrc.sh
Sorted output of sortsrc.sh
1
2
3
3
5
66
78
FINDING EVEN OR ODD
PROGRAM:
clear
echo "Enter the integer::"
read n
r=`expr $n % 2`
if test $r -eq 0
then
echo " $n is an even number"
else
echo " $n is an odd number."
fi
OUTPUT:
Enter the integer::
30
30 is an even number
Enter the integer::
29
29 is an odd number.
1
2 FINDING POSITIVE OR NEGATIVE
PROGRAM:
clear
echo "Enter the no:"
read n
if test $n -gt 0
then
echo "The given number $n is positive"
elif test $n -lt 0
then
echo "The given no. is negative"
else
echo "The given no $n is zero"
fi
OUTPUT:
Enter the no:
20
The given number 20 is positive
Enter the no:
-30
The given no. is negative
GENERATING ODD NUMBERS
PROGRAM:
clear
echo "Enter the value"
read n
i=1
echo "odd number upto $n"
while test $i -le $n
do
echo $i
i=`expr $i + 2`
done
OUTPUT:
Enter the value
10
odd number upto 10
1
3
5
7
9
REVERSING A NUMBER
PROGRAM:
clear
echo "REVERSING A NUMBER"
echo "Enter a number"
read n
i=0
r=0
while [ $n -ne 0 ]
do
i=`expr $n "%" 10`
r=`expr $r "*" 10`
r=`expr $r "+" $i`
n=`expr $n "/" 10`
done
echo "REVERSED NO IS $r"
OUTPUT:
REVERSING A NUMBER
Enter a number
12345
REVERSED NO IS 54321
1 FIBONACCI SERIES
PROGRAM:
clear
echo "FIBONACCI SERIES"
echo "Enter number of terms"
read n
echo " "
a=0
b=1
i=3
echo $a
echo $b
while [ $i -le $n ]
do
s=`expr $a "+" $b`
echo $s
a=$b
b=$s
i=`expr $i "+" 1`
done
OUTPUT:
FIBONACCI SERIES
Enter number of terms
8
0
1
1
2
3
5
8
13
2
3 FACTORIAL
PROGRAM:
clear
echo "FACTORIAL"
echo "Enter a number"
read n
echo " "
i=1
fact=1
while [ $i -le $n ]
do
fact=`expr $fact "*" $i`
i=`expr $i "+" 1`
done
echo "Factorial is $fact"
OUTPUT:
FACTORIAL
Enter a number
6
Factorial is 720
REVERSING A STRING
PROGRAM:
s=`echo $1 | wc -c`
while [ $s -gt 0 ]
do
temp=`echo $1 | cut -c $s`
s=`expr $s "-" 1`
temp1=`echo $temp1$temp`
done
echo "REVERSED STRING IS: $temp1"
OUTPUT:
[cse32@localhost cse]$ sh revstr computer
REVERSED STRING IS: retupmoc
PATTERN SEARCHING: 1
PROGRAM:
if ( grep while a1 )
then
echo pattern found in a1
elif ( grep ee a2)
then
echo pattern found in a2
else
echo not found
fi
OUTPUT:
ee
pattern found in a2
1 PATTERN SEARCHING: 2
PROGRAM:
clear
ch=1
while [ $ch -ne 0 ]
do
echo SEARCHING PATTERN
echo WORDS
echo "0. Exit"
echo "1. Clear"
echo "2. While"
echo "3. Echo"
echo "Enter Ur Choice :"
read ch
case $ch in
1) echo " Check wheather Clear Command"
echo Enter the File name
read file
if (grep clear $file)
then
echo Pattern Found
else
echo Not Found
fi;;
2) echo " Check the While Statement"
echo Enter the File name
read file
read file1
if (grep while $file)
then
echo Pattern Found in $file
elif (grep while $file1)
then
echo Pattern Found in $file1
else
echo Not Found
fi;;
3) echo " Check the echo Command"
echo enter the file name
read file
while grep echo $file
do
echo Pattern Found in $file
exit
done;;
esac
done
OUTPUT:
SEARCHING PATTERN
WORDS
SEARCHING PATTERN
WORDS
0. Exit
1. Clear
2. While
3. Echo
Enter Ur Choice :
1
Check wheather Clear Command
Enter the File name
ser.sh
clear
if (grep clear $file)
Pattern Found
SEARCHING PATTERN
WORDS
0. Exit
1. Clear
2. While
3. Echo
Enter Ur Choice :
2
Check the While Statement
Enter the File name
ser.sh
while [ $ch -ne 0 ]
if (grep while $file)
elif (grep while $file1)
while grep echo $file
Pattern Found in ser.sh
SEARCHING PATTERN
WORDS
0. Exit
1. Clear
2. While
3. Echo
Enter Ur Choice :
3
Check the echo Command
enter the file name
ser.sh
echo SEARCHING PATTERN
echo WORDS
echo "0. Exit"
echo "1. Clear"
echo "2. While"
echo "3. Echo"
echo "Enter Ur Choice :"
1) echo " Check wheather Clear Command"
echo Enter the File name
echo Pattern Found
echo Not Found
2) echo " Check the While Statement"
echo Enter the File name
echo Pattern Found in $file
echo Pattern Found in $file1
echo Not Found
3) echo " Check the echo Command"
echo enter the file name
while grep echo $file
echo Pattern Found in $file
echo continue....
Pattern Found in ser.sh
FIRST OCCURANCE OF A PATTERN
PROGRAM:
clear
if grep $1 $2
then
clear
echo The first occurance of $1 in $2 is
grep -n -m 1 $1 $2
elif grep $1 $3
then
clear
echo The first occurance of $1 in $3 is
grep -n -m 1 $1 $3
else
clear
echo $1 was not found
fi
OUTPUT:
[cse64@localhost cse64]$ sh ifgrepdisp.sh 1 ifgrep.sh ifelgrep.sh
The first occurance of 1 in ifgrep.sh is
2:if grep $1 $2
SYSTEM CALLS OF UNIX OPERATING SYSTEM
THE FORK SYSTEM CALL
PROGRAM:
#include
int main()
{
int pid;
pid=fork();
if(pid==0)
{
printf("child process id is %d\n ",getpid());
printf("parent process id is %d\n",getpid());
}
else
{
printf("parent process id is %d\n ",getpid());
printf("parent of parent process %d\n",getpid());
}
return 0;
}
OUTPUT:
[CSE@localhost ~]$ gcc forksys.c
[CSE@localhost ~]$ ./a.out
child process id is 4226
parent process id is 4226
parent process id is 4225
parent of parent process 4225
1
2 THE GETPID SYSTEM CALL
PROGRAM:
#include
int main()
{
int p,pp;
p=getpid();
pp=getppid();
printf("Child process id : %d \n" , p);
printf("Parent Process id : %d \n" , pp);
return 0;
}
OUTPUT:
[CSE@localhost ~]$ gcc getid.c
[CSE@localhost ~]$ ./a.out
Child process id : 4238
Parent Process id : 4191
THE STAT SYSTEM CALL
PROGRAM:
#include
#include
#include
#include
main(int argc,char** argv)
{
char* fname;
struct stat buf;
fname=*++argv;
if(stat(fname,&buf)==0) {
printf("The uid of %s is %d\n",fname,buf.st_uid);
}
else {
perror("stat");
exit(1);
}
exit(0);
}
OUTPUT:
[cse@localhost cse]$ ./a.out stat.c
The uid of stat.c is 564
OPENDIR AND READDIR SYSTEM CALLS
PROGRAM:
#include
#include
#include
main(int argc, char** argv)
{
DIR* pDir;
struct dirent* pDirent;
struct stat buff;
char* filename;
filename=*++argv;
if((pDir=opendir(filename))==NULL)
printf("can not open this directory");
else
{
printf("Name\tMode\tIno\tUID\tAtime\n");
while((pDirent=readdir(pDir))!=0)
{
if(stat(pDirent->d_name, &buff)==0)
printf("%s\t%d\t%d\t%d\t%d\n", pDirent->d_name, buff.st_mode,
buff.st_ino, buff.st_uid, buff.st_atime);
}
}
}
OUTPUT:
[root@server ~]# gcc ordir.c
[[root@server ~]# ./a.out xxx
Name Mode Ino UID Atime
a.out 33261 25004913 0 1262082910
.. 16877 2 0 1262082804
. 16872 25001985 0 1262082906
I/O SYSTEM CALLS OF UNIX OPERATING SYSTEM
/* OPENING AND CLOSING FILES
PROGRAM:
#include
#include
#include /* defines options flags */
#include /* defines types used by sys/stat.h */
#include /* defines S_IREAD & S_IWRITE */
static char message[] = "OPEN SYSTEM CALL";
int main()
{
int fd;
char buffer[80];
/* open datafile.dat for read/write access (O_RDWR)
create datafile.dat if it does not exist (O_CREAT)
return error if datafile already exists (O_EXCL)
permit read/write access to file (S_IWRITE | S_IREAD)
*/
fd = open("sss.txt",O_RDWR | O_CREAT | O_EXCL, S_IREAD | S_IWRITE);
if (fd != -1)
{
printf("sss.txt opened for read/write access\n");
write(fd, message, sizeof(message));
lseek(fd, 0L, 0); /* go back to the beginning of the file */
if (read(fd, buffer, sizeof(message)) == sizeof(message))
printf("\"%s\" was written to sss.txt\n", buffer);
else
printf("*** error reading sss.txt ***\n");
close (fd);
}
else
printf("*** sss.txt already exists ***\n");
exit (0);
}
OUTPUT :
[root@server ~]# gcc ofile1.c
[root@server ~]# ./a.out
sss.txt opened for read/write access
"OPEN SYSTEM CALL" was written to sss.txt
READ SYSTEM CALL
PROGRAM :
#include
#include
main()
{
int fd;
char lilbuf[0],bigbuf[1024];
fd=open("./aaa.txt",O_RDONLY);
read(fd,lilbuf,0);
read(fd,bigbuf,1024);
printf("bigbuff\n %s",bigbuf);
}
OUTPUT:
Content of aaa.txt
Operating System Lab
WRITE SYSTEM CALL
PROGRAM:
#include
#include
int main()
{
int fd,i;
char buf[512];
for(i=0;i ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.