You are on page 1of 22

Lab Cycles

Lab Cycle -1 (Practicing UNIX Commands)


UNIX Commands Exercise-1
UNIX Commands Exercise-2
Lab Cycle -2 (Essential Shell Programming)
Bash Shell Environment Exercise-1(Assignment)
Shell Programming Exercises-1
Lab Cycle -3 (Advanced Shell Programming)
Shell Programming Exercises-2
Shell Programming Exercises-3
Lab Cycle -4 (Files)
UNIX File Subsystem Programming Exercises-1
UNIX File Subsystem Programming Exercises-2
UNIX File Subsystem Programming Exercises-3
Lab Cycle -5 (Process, Signals)
UNIX Process Subsystem Programming Exercises-1
UNIX Process Subsystem Programming Exercises-2
Lab Cycle -6 (IPC, Advanced I/O, Terminal I/O)
UNIX IPC Programming Exercises-1
UNIX I/O Programming Exercises-1
References:
1. Advanced Programming in the UNIX® Environment: Second Edition
by W. Richard Stevens, Stephen A. Rago
Publisher: Addison Wesley Professional/ Pearson
2. UNIX Systems Programming: Communication, Concurrency, and Threads
by Kay A. Robbins, Steven Robbins
Publisher: Prentice Hall PTR
3. Beginning Linux® Programming Third Edition
by Neil Matthew, Richard Stones
Publisher: Wiley Publishing, Inc.
4. Advanced Unix Programming, Second Edition
by Mac J. Rochkind
Publisher: Addison Wesley Professional/ Pearson
5. Advanced Linux Programming, First Edition
by Mark Mitchell, Jeffrey Oldham, and Alex Samuel
Publisher: New Riders
Lab Cycle -1
UNIX Commands Exercises-1
Refer Sample Question 1, Commands and Special Characteristics at the end of
this document.
1. Copy the file /etc/passwd and /etc/group into your home directory and Perform
Sort Command on the passwd file
o sorting on field 3 based on the numeric order
o reverse sort using the -r switch on field 3
o store out put in a file name OUTPUT
o Perform sort by ignore case using –f switch on name field( Create a new file
name INPUT with Tab as a Delimiter )
o outputs only unique lines using –u switch
2. Create a file that have sorted list of only UID’S
3. Sort the group file. Swap fields 2 and 3 of it. Call it group1. Display the n
ew file.
4. Merge two sorted files ( file1=UID’S, file2=GID’S)
5. Perform sort on the 2 and 4 fields (Create a new file name INPUT with Tab as
a
Delimiter and having repetition of data in the fields)
6. Create a file that have list of UID’S, GID’S and Home Directory
7. Combine the contents of the file with the input from the keyboard and then ca
rry
out sorting
8. Sort only the input from the standard input (keyboard)
9. List unique shells that are currently being used on your system
10. List username, the userid and the shell (fields 1,3 and 7 from /etc/passwd).
11. What is the alternate method of specifying the delimter apart from “ “. How do
you check whether the table is sorted or not.
12. Write a Grep command to search for a word Either Rebbaca or rebbaca in a fil
e
13. Write a Grep command to search for a four letter word whose first letter is
a ‘b’
and last letter ‘k’
14. Write a Grep command that will returns only filenames containing a match
15. Write a Grep command that will returns only number of matches.
16. Write a Grep command that will dsiplay 5 lines before the matched string
17. Using cat command how can we create a file and enter the text
18. How can we Create 3 empty files using touch command in single step
19. How can we Concatenate the contents of two files and store them in the third
file
20. How can we Concatenate the contents of two files and append them in the thir
d
file
21. Display the current login users
22. What is the difference between listing the contents of directory play with l
s -l and
ls -L?
23. Create a file called hello.txt that contains the words "hello world". Can yo
u use
"cp" using "terminal" as the source file to achieve the same effect?
24. Copy hello.txt to terminal. What happens?
25. Use grep to isolate the line in /etc/passwd that contains your login details
.
26. What does the cut command do? Can you use it together with w to produce a li
st
of login names and CPU times corresponding to each active process? Can you
now (all on the same command line) use sort and head or tail to find the user
whose process is using the most CPU?
27. Multiple jobs can be issued from the same command line using the operators ;
,
&& and ||. Try combining the commands cat nonexistent and echo hello using
each of these operators. Reverse the order of the commands and try again. What
are the rules about when the commands will be executed?
28. Use ps, w and top to show all processes that are executing.
29. Use finger or who to get a list of users on the machine.
30. Create a new Directory LABTEMP and Copy the files from /var/log in to it and
display the files
a. whose first alphabet is consonant
b. that do not begin with uppercase letters
c. that has an extension of exactly three characters
31. Display all the files including files in the subdirectories
32. List all files with a trailing symbol showing their type
33. Long listing of all the files in the order of their last access time
34. Display machine details
35. Change the file Access Date to older date for a group of files
36. Change the file modified Date to future date
37. Use the date and who commands in sequence (in one line) such that the output
of
the date will display on the screen and the output of who will be redirected to
a
file called myfile2.Use the more command to check thee contents of myfile2.
38. Print your user-id and group id s
39. Display Disk Usage for a particular directory
40. Show who is logged on and what they are doing.
41. How to find out what kind of file it is.
42. Explore linux Directories /home, /proc, /sbin and find out their purposes
43. how To see the permissions on a file
44. Just login with your common user ID.
45. Which release are you running?
46. How many hours has the system been running?
47. Use the cut command on the output of a long directory listing in order to di
splay
only the file permissions. Then pipe this output to sort and uniq to filter out
any
double lines. Then use the wc to count the different permission types in this
directory.
48. Try F option for ls on /dev Directory. Which is your identify your tty (term
inal)
device? Is your tty character-oriented or block-oriented? Who is the owner of
your tty?
49. Create a Link for the file and display its inode number
50. What command can be used to display the current memory usage?
51. Why Cal 9 1752 give abnormal result
52. Try ln -s /etc/passwd passwords and check with ls-l. Have you found any thin
g
extra?
53. Display first 15 lines of a file
54. Display list 15 lines of a file
55. Echo the string with white spaces
Sample Question: 1
Use the cat command to create a file containing the following data. Call it myta
ble.
Sort the mytable. Swap fields 2 and 3 of mytable. Call it mytable. Print the new
file
mytable.
Ans) a) Creating the file mytable. Use tabs to separate the fields.
$ cat > mytable
1425 Ravi 15.65
4320 Ram 26.27
6830 Raj 36.15
1450 Sita 21.86
^d
b) Displaying the file mytable contents: $ cat mytable
c) Sorting the file mytable: $ sort mytable
d) Swaping the fields 2 and 3
$ cut –f 1 mytsble >file1
$ cut -f 2 mytable >fie2
$ cut -f 3 mytable >file3
$ cut -f 4 mytable >file4
$ paste file1 file3 file2 file4 >mytable
$ cat mytable
f) Printing the file mytable: $ lpr mytable
Informational Commands
Display Commands:
Special Characteristics:
Lab Cycle -1
UNIX Commands Exercises-2
1. Count the number of users who logged in and display the result.
2. Count the number of files in the current directory
3. Count the number of differences( in term of lines) between two files
4. Display the file /etc/passwd from the 45th line using the more command and st
art the vi
editor on the current file and current line. Hint: Press h or ? Button while vie
wing the
file with more command to get the help
5. Open the file /etc/passwd using more command and display the file backwards (
i.e., from
the last line).What sub command should be pressed to know the line number
6. Display the contents of the file /etc/passwd one screen at a time and Search
a pattern in it
7. How can we change the prompt of the more command
8. How can we suppress contiguous multiple blank lines present in the file with
a single
blank
9. If more is used to display multiple files what sub command is required
o To Display the current file name and file number
o Switch to the next file
o Switch to the Previous file
o Scroll n lines in the current file
o Skip k lines in the current file
10. How an ordinary shell command can be executed while viewing the file with mo
re
command. Try date command
11. Perform the Following
o Change the file access and modification time to the current time
o Change the file access and modification time to the specified time
o Change the file access and modification time to the specified time of the spec
ified file
with the one specified as file, rather than the current time
12. Display the details of the user by using the user name Hint: finger
13. What is the best and fastest way to know the location of the program or comm
and that
system will execute? Hint: Type
14. Perform the Following
o Display May 05 using the date command
o Display DATE: todaydate using the date command
TIME: time
15. Which options are required for who command to display the column headers and
more
details list?
16. How do you know your machine’s name?
17. How do you spell check a file and display the mistakes Hint: ispell
18. Calculate sum of two numbers using expr
19. Perform the Following
o How to copy entire directory using cp command
o How to remove a directory using rm command
o How to rename a directory
o How do you determine the type of the file prog.c
20. Create a file using cat and find the number of lines, words and characters i
n it.
21. Perform the Following
o How do you split a file in to multiple files? Hint: split
o How do you compare files?
o How do you display \ using echo command?
22. Use escape sequences \t, \n, \a and \f in the sample text and display it usi
ng echo
command. Hint: The ^G character ring a bell its corresponding escape sequences i
s \a
23. Which special character the shell uses to remove the special meaning of any
Meta
character placed after it. List the inode of the files chap*, chap[1]
Hint: chap* chap[1] are the files created by you.
24. What happens when you enter a shell metacharacter * with the echo command.
25. How do you know your terminal name?
26. Check whether the output is similar for both
$ wc < infile and $ wc infile
27. Perform the Following
o Cat the input first from file1, then standard input, and then file2
o Cat the input first from standard input, and then from file1
o Echo a message on someone’s terminal screen
o Echo a message on your terminal screen Hint: use tty
28. Two or more commands can be combined, and the aggregate output can send to a
n output
file. How to perform it
29. How do we save both standard output and error streams in the same file using
the stream
merging mechanism
30. Display the contents of the recent modified file using vi where vi’s argument
is given by
command substitution
31. Display the size of all the files in KB, MB, GB using ls command
32. Display the contents of the directory using ls command
33. Display the contents of the directory in long list having uid and gid using
ls command
34. Write a unix command to compare a file with standard input
35. How do you redirect the standard output to a file that will incinerate? Give
example
36. compare two files in which one of them is the output of the other command
37. Find the following forms are equivalent are not
Cat > foo and Cat - > foo
Cat >> foo and Cat - >> foo
38. Perform the Following
o Check $ > newfile < infile wc and give result
o Redirect error message to file ERROR on cat command for non existent file
o Redirect standard output and standard error streams for cat command with an
example in one step.
39. Save the output of the who command in a file, as well as display it
40. Save the output of the who command in a file, display it, display lines coun
t on the
terminal.
41. Display the text There are n files in the current directory
Here: n=count or number of files in your current directory
42. Display calendar for the year 1980 where this argument is given by date comm
and
43. Display the text The date today is current date
44. When will wc < chap0[1-5] work? Create a file chap0[1-7]
45. How will you mark the completion of a command with a beep?
46. Change the permissions of your file infile with only execution, read permiss
ion to others
and execution permission to group.
47. Display all filenames available in your home directory beginning with an alp
habet,
irrespective of case
48. Perform the following
a. Copy recursively three directories to the other directory in a single step
b. Copy all files from three directories to the other directory in a single step
c. Copy all .c files from a directory to the other directory in a single step
49. Create a shareable directory where any one can use it but cannot delete it.
50. Perform the Following
o Create a file with sticky bit and view its permissions by ls –l
o Check whether sticky bit is there for Vi editor or not
o Make a directory in such a way that all the files and sub-directories in the d
irectory
executable by all users
51. Display the umask value
52. Change the umask value and identify the difference with the earlier using to
uch, ls –l
53. Logout and see whether the umask hold the new value or not
54. How can we create a link for a directory? Is it hard or soft link?
55. Display data of the file containing nonprinting characters in ASCII octal va
lue
56. Perform the following
o Compress and uncompress a file ERROR
o Zip a group of files (ERROR, newfile, infile, passwd, group) and unzip them
o Gzip a group of files and gunzip them
o Bzip2 a group of files and bunzip2 them
57. How can we View the contents of the compressed file and how can we redirect?
58. Using the tar archival command perform the following
o Create an archive
o Extract files from archive
o Display files form archive
o Specify the archive
59. Convert a file from ASCII to EBCDIC and alphabetic characters to lower case
60. How do we create a image of your floppy on disk using dd command
61. Request for a printout and cancel it and Check who are in the queue
62. Explore /proc. Display the contents of the files interrupts, devices, cpuinf
o, meminfo and
uptime using cat. Can you see why we say /proc is a pseudo-filesystem which allo
ws
access to kernel data structures?
63. Create a new file1 and perform the following using chmod command with relati
ve
permissions
o Give executable permission only to the owner
o Give executable permission to all
o Assign the same set of permissions to a group of files
o Restore the original permissions to the new file1. hint: chmod also accepts
multiple expressions delimited by commas
o Give write and execute permissions for others
64. Imagine you were working on a system and someone accidentally deleted the ls
command (/bin/ls). How could you get a list of the files in the current director
y? Try it.
65. Create a new file2 and perform the following using chmod command with absolu
te
permissions
o Assign read and write permissions to all categories
o Give executable permission to all
o Restore the original permissions to the new file2
o Assign all permissions to the owner, read and write permissions to the group,
and
only execute permission to the others
66. Write a UNIX command to descend a directory hierarchy and apply the executab
le
permission to all for every file and subdirectory it finds
a. including hidden files
b. not including hidden files
67. Describe three different ways of setting the permissions on a file or direct
ory to r--r--r--.
Create a file and see if this works.
68. How do we change File Owner and Group Owner for a file?
69. Type umask 000 and then create a file called world.txt containing the words
"hello
world". Look at the permissions on the file. What s happened? Now type umask 022
and
create a file called world2.txt. When might this feature be useful?
70. How do we set SUID to a file
71. How do we set GUID to a file
72. Perform the following
o Display the lines from the file /etc/passwd that start with f.
o Display the lines from the file /etc/passwd that end with h.
o Use the grep command to display the lines from the file /etc/hosts.deny that a
re NOT
comment lines (the comment lines are the lines that start with #).
o Use the grep command to display all lines from any file in /etc/init.d that st
art with
echo.
o Which files in /etc/init.d contain the word tr?
Note: use the man command to lookup option for grep that searches for the word "
tr"
instead of the string "tr".
Lab Cycle -2
Bash Shell Exercises-1
1. Execute the following shell variables
o $HOME
o $PATH
o Which variable instructs the shell about the route it should follow to locate
any shell command?
o To include a directory /usr/xpg4/bin in your search list how you will
reassign the PATH variable
o $MAIL
o $MAILCHECK
o $IFS
o $LOGNAME
o $TERM
o $SHELL
o How you can confirm the contents of $IFS Variable by taking its octal
dump Hint: od –bc
o To customize our shell environment how do you set, unset, and display
options
2. Perform the following for your login
o Disallow ctrl+d to exit the shell for your login
o Does not allow redirection to clobber exiting file
o Use Vi for command-line editing and history file
o Disable wildcard expansion
o Change the interrupt key ^c to ^l
o How do you assign short-names for commands you may be using quite
frequently? Perform it on ls -l.
o Change the end of file key to ^a
o Display cal and your current directory every time you login
3. How do you edit the current and previous command lines?
o Perform with an example by deleting a character, 3 characters and a word.
o How do you paste this word elsewhere in the line?
o How do you recall a previous command?
o How do you recall fifth-most recent command?
o How do you get the line you are looking for if you over shoot?
4. Perform the following
o How do you Increase the size of your History to 20000? Hint: HISTSIZE
o How do you executes the previous to previous command
o Repeat the command with event number 33 and execute it
o Repeat the command with event number 33 with out executing it
5. Perform the following
o How do you search history list for previous commands. How do you
repeat the search? If you over shoot how do you come back
o Execute the command prior to the previous one
o How do you perform a substitution on the immediately previous
command?
o List out the last 5 commands you used in your computer
o Repeat the last command beginning with v
o How do you perform substitution in recalled command ls
6. Perform the following
o How do you change or revert to your most recent previous directory?
o Which variable is used to store the last argument of the last command?
Perform it with an example.
o How do you display Event number in prompt?
o How do you display PWD in prompt?
o How do you display hostname of your computer in prompt?
7. Perform the following
o How do you list alias available in your shell?
o How do you incorporate positional parameters in an alias? Perform it on
cd.
o How do you redefine and unset an alias? Perform it with an example.
8. How do you display all the current settings of the terminal?
9. How do you overwrite the protection feature noclobber?
10. Which file simply incinerates all output written to it and accepts any strea
m with
out growing its size? Perform with an example
11. How a variable can also be assigned the value of another variable? Perform w
ith
an example
12. How do you concatenate two shell variables? Perform with an example
13. Create a local variable in the parent shell then run a Bash sub-shell with s
h and
check whether you can see the variable there or not
14. Using expr perform four basic arithmetic operations as well as the modulus
15. How to change echoe: Whether backspacing should erase the character using st
ty
16. How to change echo: Entering a password through a shell script using stty
17. Perform the following
o Display all the variables available in the current shell
o Display all the environment variables available in the current shell
18. Write a shell script that displays the calendar for the current month, date
and shell.
19. Write an interactive shell script to search a pattern in the file
20. Write a shell script to search a pattern in the file using command line argu
ments
21. Write a shell script that will display Exit Status 0, 1, 2 and 3 as output
22. Write a shell script that will use logical operators
Try using test or [ ]
23. Using numeric comparison operators compare two numbers and display the exit
status on
o Equal to
o Not equal to
o Greater than
o Lesser than or Equal to
o Greater than or Equal to
o Lesser than
24. Using string tests Compare two strings or a single one for a null value and
display
the exit status on
o Equal to
o Not equal to
o Str is Not a null string
o Str is a null string
o Str is assigned and not null
25. Using file-related tests Checks a file’s attributes and display the exit statu
s on
o Is regular file
o Is readable
o Is writable
o Is executable
o Is a directory
o Has a size greater than zero
o Exists
o SUIB bit set
o Sticky bit set
o Symbolic link
o f1 is newer than f2
o f1 is older than f2
o f1 is linked to f2
Lab Cycle -2
Shell Programming Exercises-2
Refer sample c code at the end of this document.
1. Write a shell script to find the sum of first N natural numbers
2. Write a shell script to read n numbers from the user and display its sum
3. Write a shell script to read n numbers from the user from the command line an
d
display its sum
4. Write a shell script to read 10 numbers from the user and to find the sum and
average of the numbers.
5. Write a shell script to generate even numbers and to calculate its sum
6. Write a shell script for swapping two numbers (using only two variables)
7. Write a shell script to find the count and sum of even and odd numbers separa
tely
8. Write a shell script to calculate the value of Xn
9. Write a shell script to find the factorial of a given number
10. Write a shell script to find the sum of digits in an integer
11. Write a shell script to count the number of digits in an integer
12. Write a shell script to find whether the given number is Armstrong or not
13. Write a shell script to print the multiplication table of the given number
14. Write a shell script to print all divisors of a given integer
15. Write a shell script to generate Fibonacci series.
a) Program to find Fibonacci number
#include<stdio.h>
main()
{
int n,f1,f2,f3;
f1=1;
f2=1;
printf("enter the no. upto which fibonacci series is to be displayed");
scanf("%d",&n);
if(n!=0)
printf("%d ",f1);
if(n>1)
printf("%d ",f2);
while((f3=f1+f2)<=n)
{
f1=f2;
f2=f3;
printf("%d ",f3);
}
printf("\n");
}
OUT PUT:
[unixlab@klce-cse2 ~]$ cc fib.c
[unixlab@klce-cse2 ~]$ ./a.out
Enter no of numbers6
0 1 1 2 3 5
b) Program to find Factorial of a given number
#include<stdio.h>
main( )
{
int n,i;
long int fact=1;
printf("enter the no.for which factorial is to be obtained");
scanf("%d",&n);
for(i=1;i<=n;++i)
fact=fact*i;
printf("factorial of %d is %ld\n",n,fact);
}
output:
[unixlab@klce-cse2 ~]$ cc facto.c
[unixlab@klce-cse2 ~]$ ./a.out
Enter a number5
Factorial of given number=120
Lab Cycle -3
SHELL Programming Exercises-2
Refer: Sample Questions at end of this document
1. Write a shell script to determine whether the given number is prime or not
2. Write a shell script to find the sum of negative numbers given by the user an
d discarding the
positive ones
3. a. Write a shell script to find the length of the string Refer: Sample Questi
ons  
 = echo $str
Hint: var  | wc –c
len = exp $var – 1
b. Write a shell
 script to convert lowercase
 letters to its uppercase
Hint: var
 = echo $str | tr [a-z] [A-Z]
 or
var = echo $str | tr ‘[a-z]’ ‘[A-Z]’
4. Write a shell script to copy a string into another string, character by chara
cter
Refer: Sample Questions  
Hint: in order to cut a single character use var = echo $str | cut –c 1
Hint: Concatenate of two shell variables z=$x$y
5. Write a shell script to reverse the string
6. Write a shell script to count the number of vowels in the string
7. Write a shell script to count the number of occurrence of a particular charac
ter in the string
8. Write a shell script to replace a particular character in the string
9. Write a shell script to display Good Morning, Good Afternoon, Good Evening an
d Good Night
as appropriate when this shell script is executed.
Hint: OR or AND between two conditions is possible with test
[ var –op var –o var –op var ], [ var –op var –a var –op var ]
10. Write a shell script to read a user name and to find whether the user is cur
rently logged in or not
11. Write a shell script to find whether the file is a directory or an ordinary
file (Without using test
command) and using test command
Hint: ls –l > temp
If (grep $name temp > temp1); then 
Line = cat temp1 | tr –s “ “ | cut –d “ “ –c 1
fi
12. Write a shell script to find whether the file is a directory or an ordinary
file
(With and without using test command) by reading any number of filenames from th
e command
line
Sample Questions
1. How to calculate the length of the string: see the example
Method 1:
$ expr “abcdefghijkl” : ‘.*’ space on either side of : required
$ 12
or
$ str = abcdefghijkl
$ expr “$str” : ‘.*’
$ 12
Method 2:
$ str = “abcd all”
$ echo ${#str}
$ 8
2. How to extract a substring: See the example (here 2 digit year from a 4-digit
string)
$ str = 2009
$ expr “$str” : ‘..\(..\)’
$ 09
3. How to locate the position of a character: expr can also return the location
of the first
occurrence of a character inside a string.
See the example: to locate the position of the character d in the string value o
f $stg, you
have to count the number of characters which are not d ([^d]*d), followed by d
$ str = abcdefghijkl ; expr “$str” : ‘[^d]*d’
$ 4
4. Extracting a string by pattern matching
See the example
#is used to match at the beginning
% is used to match at the end
${var#pattern} Shortest statement that matches pattern at the beginning of $var
${var%pattern} Shortest statement that matches pattern at the endof $var
${var##pattern} Longest statement that matches pattern at the beginning of $var
${var%%pattern} Longest statement that matches pattern at the end of $var
a) To remove a extension from a file name
$ filename=quotation.txt
$ echo ${filename%txt}
$ quotation txt stripped off
b) To delete a string that matches the pattern */ but at the beginning (here * i
s meta
character)
$ filename=”/var/mail/henry”
$ echo ${filename##*/}
$ henry /var/mail/ stripped off
5. We can use ${str} in side the if control structure such as
If [ ${#str} –gt 20 ] ; then
Lab Cycle -3
SHELL Programming Exercises-3
Refer: Sample Questions at end of this document
Write a shell script to find whether the file is a directory or an ordinary file
(Without using test
command) and using test command
Hint: ls –l > temp
If (grep $name temp > temp1); then 
Line = cat temp1 | tr –s “ “ | cut –d “ “ –c 1
fi
1. Write a shell script to count the number of ordinary files and directory file
s in the current
working directory
2. Write a shell script that accepts an alphabet from the user and displays all
filenames
starting with that alphabet in the current working directory
3. Write a shell script to find whether the file has execute permission or not (
without using
test command)
4. Write a shell script to find the file with the maximum size in the current wo
rking
directory (without using the sort command)
5. Write a shell script, which reads file names from the current working directo
ry and to
display the names of files to which you have read, write and execute permissions
6. a. Write a shell script to read a filename from the user and to display the o
wner of the file
b. Write a shell script to read a filename from the user and to display its file
permission.
7. Write a shell script, which reads a filename and assigns read, write and exec
ute
permissions for the file by asking a question. If the answer is “Y” then it should d
o so
else it should abort the operation.
8. Write a shell script to calculate the time taken by the user since logged in
9. Create a shell script for a telephone book application. Display a menu for th
e following
functions.
1. Add an entry
2. Display all matches to a string
3. Sort and display the file
4. Delete all entries that match a string
5. exit the program
o Using the phone list below:
o Add a new name to the phone book file
o Display all matches to a name or phone number
o Sort the phone book file by last name
o Delete an entry
Print the results from each sequence of commands
Data File (tabs between fields)
Gene Smith 732 946-4691
Henry Brown 908 922-5820
Harry Crown 609 566-4515
Jim Zark 732 842-1910
Tom Mann 908 264-5321
Jack Spratt 908 264-4816
Joe Bram 609 521-4841
10. Create a simple menu program that will display the following options and con
tinue until
the exit option is chosen. Catch all input errors issue an error message and con
tinue. The
menu options are:
a. Display the time and date
b. Display the contents of the user directory
c. Display that processes that are running
d. Display who is on the system
e. Exit the program
11. Write a script called leap_year.sh that takes a year as input and determines
if it’s a leap
year. If the user does not enter a correct leap year then the script should comp
ute the next
leap year after the date entered as an argument. The script command line and its
response
should look like the following:
$Enter the year
$201
$201 is not a leap year.
$The closet leap year after that year is 204
$Enter the year
$2008
$2008 is a leap year.
Pseudocode to determine whether a year is a leap year or not:
if year modulo 400 is 0 then leap
else if year modulo 100 is 0 then no_leap
else if year modulo 4 is 0 then leap
else no_leap
12. Write a script called count_linesinfiles.sh that counts the number of ordina
ry files (not
directories) in the current working directory and its sub-directories. For each
ordinary file
found your script could count the number of lines in file and print the total nu
mber of
lines for files in the directory tree rooted at the current working directory.
Counting lines of all files...
23 ./count.sh
1 ./a.java
24 Total
*************************
Number of files found: 6
*************************
13. Write a scripted called birthday_match.sh that take two birthdays (or in the
general case
any two dates in history) of the form MM/DD/YYYY (e.g., 05/15/1959) and returns
whether there is a match if the two people where born on the same day of the wee
k (e.g.,
Friday). It should be fun to see if any of you are born on the same day of the w
eek. The
input and output to/from the script should follow this format:
$birthday_match.sh 12/01/1984 12/02/1984
The first person was born on: Sat
The second person was born on: Sun
Therefore, you are not born on the same day.
$birthday_match.sh 11/25/1984 12/02/1984
The first person was born on: Sun
The second person was born on: Sun
Jackpot: You were both born on the same day!
Sample Questions
1. How to calculate the length of the string: see the example
Method 1:
$ expr “abcdefghijkl” : ‘.*’ space on either side of : required
$ 12
or
$ str = abcdefghijkl
$ expr “$str” : ‘.*’
$ 12
Method 2:
$ str = “abcd all”
$ echo ${#str}
$ 8
2. How to extract a substring: See the example (here 2 digit year from a 4-digit
string)
$ str = 2009
$ expr “$str” : ‘..\(..\)’
$ 09
3. How to locate the position of a character: expr can also return the location
of the first
occurrence of a character inside a string.
See the example: to locate the position of the character d in the string value o
f $stg, you
have to count the number of characters which are not d ([^d]*d), followed by d
$ str = abcdefghijkl ; expr “$str” : ‘[^d]*d’
$ 4
4. Extracting a string by pattern matching
See the example
#is used to match at the beginning
% is used to match at the end
${var#pattern} Shortest statement that matches pattern at the beginning of $var
${var%pattern} Shortest statement that matches pattern at the endof $var
${var##pattern} Longest statement that matches pattern at the beginning of $var
${var%%pattern} Longest statement that matches pattern at the end of $var
a) To remove a extension from a file name
$ filename=quotation.txt
$ echo ${filename%txt}
$ quotation txt stripped off
b) To delete a string that matches the pattern */ but at the beginning (here * i
s meta
character)
$ filename=”/var/mail/henry”
$ echo ${filename##*/}
$ henry /var/mail/ stripped off
5. We can use ${str} in side the if control structure such as
If [ ${#str} –gt 20 ] ; then
6. The bash shell also supports the C-style for statements:
for (( variable assignment ; condition ; iteration process ))
do
...statements...
done
Example:
#!/bin/sh
for (( i=1; $i <= 10; i++ ))
do
echo $i
done
7. All of the shells support one-dimensional numeric arrays:
$ mytest=(one two three four five)
$ echo $mytest
one
$ echo ${mytest[2]}
three
$ echo ${mytest[*]}
one two three four five
8. break Exit from a for, while, select, or until loop.
9. Continue Resume the next iteration of a for, while, select, or until loop.
10. printf Display text using formatted strings.
$ printf “%s\n” hello
hello
$ printf “%s %d\t%s” “Hi There” 15 people
Hi There 15 people
11. Syntax for "function" is:
<name of function> ()
{ # start of function
statements
} # end of function
Example:
#!/bin/sh
sumcalc ()
{
sum=$[$1 + $2]
}
echo "Enter the first number:"
read num1
echo "Enter the second number:"
read num2
sumcalc $num1 $num2
echo "Output from function sumcalc: $sum"
12. Return Force a function to exit with a value that can be retrieved by the ca
lling
script.
The return command causes functions to return. Return takes a single numeric par
ameter
that is available to the script calling the function. If no parameter is specifi
ed, return
defaults to the exit code of the last command.
Lab Cycle -4
Refer System Call prototypes at the end of this document
$man 2 systemcall name to get help Ex: $man 2 open
1. Write a unix system program to copy standard input to standard output
Hint: while ((n= read ( 0, buf, sizeof(buf) ) ))>0)
2. Write a unix system program to read slow from the standard input and write to
standard
output Hint: for (;;)
-------
Sleep (3);
3. Write a unix system program to copy data from one file /etc/passwd to other f
ile pass.bak
4. Write a unix system program to copy data from one file to other file where fi
les were
given as command line arguments
5. Write a unix system program to copy data from one file and append to other fi
le
6. Write a unix system program to read a file in reverse
7. Write a unix system program that tests its standard input to see whether it i
s capable of
seeking.
8. Write a unix system program that creates a file with a hole in it.
9. Write a unix system program that creates two files, one with a umask of 0 and
one with a
umask that disables all the group and other permission bits.
System call prototypes:
open Function:
A file is opened or created by calling the open function.
#include <fcntl.h>
int open(const char *pathname, int oflag, ... /* mode_t mode */ );
Returns: file descriptor if OK, -1 on error
creat Function:
A new file can also be created by calling the creat function
#include <fcntl.h>
int creat(const char *pathname, mode_t mode);
Returns: file descriptor opened for write-only if OK, -1 on error
close Function:
An open file is closed by calling the close function
#include <unistd.h>
int close(int filedes);
Returns: 0 if OK, -1 on error
lseek Function:
An open file s offset can be set explicitly by calling lseek
#include <unistd.h>
off_t lseek(int filedes, off_t offset, int whence);
UNIX Systems Programming Exercises-1
Returns: new file offset if OK, -1 on error
read Function:
Data is read from an open file with the read function.
#include <unistd.h>
ssize_t read(int filedes, void *buf, size_t nbytes);
Returns: number of bytes read, 0 if end of file, -1 on error
write Function:
Data is written to an open file with the write function.
#include <unistd.h>
ssize_t write(int filedes, const void *buf, size_t nbytes);
Returns: number of bytes written if OK, -1 on error
umask Function:
umask system call sets the mask to the value specified as argument, but it also
returns the
previous value of the mask.
#include <sys/stat.h>
mode_t umask(mode_t cmask);
Returns: previous file mode creation mask
truncate Function:
The truncate and ftruncate calls can truncate a file to any desired length
#include <unistd.h>
int truncate(const char *pathname, off_t length);
int ftruncate(int filedes, off_t length);
Reference:
Advanced Programming in the UNIX® Environment: Second Edition
by W. Richard Stevens, Stephen A. Rago
Publisher: Addison Wesley Professional
Lab Cycle -4
$man 2 systemcall name to get help Ex: $man 2 open
1. Write a unix system program using umask that will change file permissions twi
ce
2. Write a program to print all error messages used by your system
3. Write a program that displays system call errors with perror
4. Write a program that will perform copy on command line arguments with error
handling (Three types of error handling techniques and five exit points)
5. Write a unix system program to read a file in reverse with error handling
(Three types of error handling techniques and five exit points)
6. Write a unix system program to navigate a directory using chdir and getcwd
7. Write a system program that list files names and inode numbers in a given
directory( ls – ia)
8. Write a system program that prints the type of file for command line argument
UNIX Systems Programming Exercises-2
Lab Cycle -4
Refer System Call prototypes and sample programs at the end of this document
$man 2 systemcall name to get help Ex: $man 2 open
1. Write a system program to display some file attributes of a particular file
2. Write a system program that list only inode numbers of all files in a given d
irectory
3. Write a system program that prints the type of file for each command line arg
ument
4. Write a system program to list only directories – uses S_IFMT and S_ISDIR macro
s
5. Write a system program to truncate a file to a particular offset using ftrunc
ate system call
6. a. Write a system program to remove a file using remove system call
b. Write a system program to rename a file using rename system call
7. a. Write a system program to link a file using link system call
b. Write a system program to open a file and unlink it
8. a. Write a system program to change the permissions of a file using chmod sys
tem call
b. Write a system program to change the groupId using chown system call
9. Write a system program using dup and dup2 called "test.c" in which entries of
file sub
system data structures are
· The first file descriptor was the original descriptor, allocated in slot 3
· The second descriptor was a copy of the first, allocated in slot 4.
· The third descriptor was a copy of the first, allocated in slot 0 that was freed
by the close (0)
statement (the standard input channel).
· The fourth descriptor was a copy of descriptor 3, copied over the existing descr
iptor in slot 2
(the standard error channel).
· Use three write system calls
o write (fd1, "what s", 6);
o write (fd2, " up", 3);
o write (0, " doc", 4);
Finally by executing the last write system call the out put must be what s up do
c?
10. Write a system program to find whether the file is a directory or an ordinar
y file
11. Write a system program to count the number of ordinary files and directory f
iles in the
current working directory
12. Write a system program to find whether the file has 755 permission or not
13. Write a system program to display the files in the current directory whose s
ticky bit is set
14. Write a system program to find the file with the maximum size in the current
working
directory
Solution to program :4
/* Program: lsdir.c --Lists only directories - Uses S_IFMT and S_ISDIR macros */
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *direntry; /* Returned by readdir() */
struct stat statbuf; /* Address of statbuf used by lstat() */
UNIX Systems Programming Exercises-3
mode_t file_type, file_perm;
if ((dir = opendir(argv[1])) == NULL)
quit("Couldn t open directory", 1);
if ((chdir(argv[1]) == -1)) /* Change to the directory before */
quit("chdir", 2); /* you starting reading its entries */
while ((direntry = readdir(dir)) != NULL) { /* Read each entry in directory*/
if (lstat(direntry->d_name, &statbuf) < 0) { /* dname must be in */
perror("lstat"); /* current directory */
continue;
}
if (S_ISDIR(statbuf.st_mode)) { /* If file is a directory */
file_type = statbuf.st_mode & S_IFMT;
file_perm = statbuf.st_mode & ~S_IFMT;
printf("%o %4o %s\n", file_type, file_perm, direntry->d_name);
}
}
exit(0);
}
unlink
int unlink (const char* fileName)
unlink () removes the hard link from the name fileName to its file. If fileName
is the last link to the file,
the file s resources are deallocated.
stat
int stat (const char* name, struct stat* buf)
struct stat {
mode_t st_mode; /* file type & mode (permissions) */
ino_t st_ino; /* i-node number (serial number) */
dev_t st_dev; /* device number (file system) */
dev_t st_rdev; /* device number for special files */
nlink_t st_nlink; /* number of links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
off_t st_size; /* size in bytes, for regular files */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last file status change */
blksize_t st_blksize; /* best I/O block size */
blkcnt_t st_blocks; /* number of disk blocks allocated */
};
There are some predefined macros defined in "/usr/include/sys/stat.h" that take
st_mode as their argument
and return true (1) for the following file types:
MACRO RETURNS TRUE FOR FILE TYPE
S_ISDIR directory
S_ISCHR character-oriented special device
S_ISBLK block-oriented special device
S_ISREG regular file
S_ISFIFO pipe
Masks to interpret the st_mode flags include
S_IFMT: File type
S_IRWXU: User read/write/execute permissions
S_IRWXG: Group read/write/execute permissions
S_IRWXO: Others’ read/write/execute permissions
Reading Directory Information: opendir (), readdir (), and closedir ()
DIR * opendir (char * fileName)
struct dirent * readdir (DIR *dir)
int closedir (DIR *dir)
opendir () opens a directory file for reading and returns a pointer to a stream
descriptor which is used as
the argument to readdir () and closedir (). readdir () returns a pointer to a di
rent structure containing
information about the next directory entry each time it is called. closedir () i
s used to close the directory.
The dirent structure is defined in the system header file "/usr/include/dirent.h
"
NAME MEANING
d_ino the inode number
d_off the offset of the next directory entry
d_reclen the length of the directory entry structure
d_name the filename
opendir () returns the directory stream pointer when successful, NULL when not s
uccessful. readdir ()
returns 1 when a directory entry has been successfully read, 0 when the last dir
ectory entry has already
been read, and -1 in the case of an error. closedir () returns 0 on success, -1
on failure.
chown
int chown (const char* fileName, uid_t ownerId, gid_t groupId)
chown () causes the owner and group IDs of fileName to be changed to ownerId and
groupId,
respectively. A value of -1 in a particular field means that its associated valu
e should remain unchanged.
Only a super-user can change the ownership of a file, and a user may change the
group only to another
group that he/she is a member of. If fileName is a symbolic link, the owner and
group of the link are
changed instead of the file that the link is referencing.
#include <unistd.h>
main ()
{
int flag;
flag = chown ("test.txt", -1, 62); /* Leave user ID unchanged */
if (flag == -1) perror("mychown.c");
}
chmod
int chmod (const char* fileName, int mode)
chmod () changes the mode of fileName to mode, where mode is usually supplied as
an octal number. The
"set user ID" and "set group ID" flags have the octal values 4000 and 2000, resp
ectively. To change a
file s mode, you must either own it or be a super-user.
#include <sys/stat.h>
main ()
{
int flag;
flag = chmod ("test.txt", 0600); /* Use an octal encoding */
if (flag == -1) perror ("mychmod.c");
}
dup
int dup (int oldFd)
int dup2 (int oldFd, int newFd)
dup () finds the smallest free file descriptor entry and points it to the same f
ile as oldFd. dup2 () closes
newFd if it s currently active and then points it to the same file as oldFd. In
both cases, the original and
copied file descriptors share the same file pointer and access mode.
They both return the index of the new file descriptor if successful, and -1 othe
rwise.
link
int link (const char* oldPath, const char* newPath)
link () creates a new label newPath and links it to the same file as the label o
ldPath. The hard link count
of the associated file is incremented by one. If oldPath and newPath reside on d
ifferent physical devices, a
hard link cannot be made and link () fails.
#include <unistd.h>
main ()
{
link ("original.txt", "another.txt");
}
truncate
int truncate (const char* fileName, off_t length)
int ftruncate (int fd, off_t length)
truncate () sets the length of the file fileName to be length bytes. If the file
is longer than length, it is
truncated. If it is shorter than length, it is padded with ASCII nulls.
#include <unistd.h>
main ()
{
truncate ("file1.txt", 10);
truncate ("file2.txt", 10);
}
remove
We can also unlink a file or a directory with the remove function. For a file, r
emove is identical
to unlink. For a directory, remove is identical to rmdir.
#include <stdio.h>
int remove(const char *pathname);
rename
A file or a directory is renamed with the rename function.
#include <stdio.h>
int rename(const char *oldname, const char *newname);
Lab Cycle -5
UNIX Systems Programming Exercises-1
1. Write a system program that lists process and user credentials (pid, ppid, ui
d, euid
gid and egid)
2. Write a system program that creates a child using fork() system call
3. Write a system program that creates a Orphan
4. Write a system program that creates a Zombie
5. Write a system program that waits for its child to terminate using wait() sys
tem
call
6. Write a system program using dup2 to execute sort command
7. Write a system program which will opens files in the parent and uses dup2 in
the
child to reassign the descriptors
8. Write a system program that shares a pipe between two process
9. Write a system program that shows the pipe use in a single process
10. Write a system program that runs two programs in a pipeline such a way that
child runs cat, parent runs tr.
11. Write a system program that runs two programs in a pipeline such a way that
child runs wc -l, parent runs who.
12. Write a system program that displays a small message and then replaced its c
ode
with “ls” executable file
13. Write a system program that demonstrates Named pipe
14. Write a system program to implement $ls > ls.out and $ls >> ls.out
15. Write a system program to implement $ wc sample.txt > newfile
16. Write a system program to implement $sort < ls.out
17. Write a system program to implement $cat – foo.txt
18. Write a system program to implement $cat foo – bar
19. Write a system program to implement $(ls –l ; cal ; date) > all.txt 2> error.t
xt
20. Write a system program to implement $ cat foo 2> error.txt and $ cat foo 2 >
>
error.txt
21. Write a system program to implement $ ls | wc –l > result.txt
22. Write a system program to implement $who | tee user.txt
23. Write a system program to implement $who | tee /dev/tty | user.txt
Lab Cycle -5
UNIX Systems Programming Exercises-2
$kill –l to display available signals
1. Write a unix system program using alaram()
2. Write a unix system program using alaram() and signal() that has a handler
specified
3. Write a unix system program that demonstrates SIGSYS and display signal
number
4. Write a unix system program that changes default disposition to ignore
5. Write a unix system program that demonstrates SIGILL and display signal
number
6. Write a unix system program that demonstrates SIGHUP, SIGQUIT,
SIGTSTP and display signals numbers
7. Write a unix system program that restores the default disposition by avoiding
the own handler
8. Write a unix system program that protects critical code and chain interrupt
handlers using kill()
9. Write a unix system program that demonstrates SIGUSR1, SIGUSR2 using
kill()
10. Write a unix system program that demonstrates SIGCHLD using kill()
11. Write a unix system program that demonstrates SIGSTOP, SIGCONT using
kill()
12. Write a unix system program that demonstrates setpgid() using kill()
13. Write a unix system program that demonstrates SIGINT and setpgid() using
kill()
14. Write a unix system program that demonstrates SIGTTIN using kill()
15. Write a unix system program that uses fork and exec to run a user-defined
program and kills it if it doesn’t complete in 5 seconds
16. Write a unix system program with a shell-like capability ( accepts user inpu
t
as a command to be executed . uses the strtok library function for parsing
command line )
Lab Cycle -6
UNIX Systems Programming Exercises-1
1. Write UNIX system program or programs to demonstrate the IPC mechanism
semaphores-oriented system calls.
2. Write UNIX system program or programs to demonstrate the IPC mechanism
shared memory-oriented system calls.
3. Write UNIX system program or programs to demonstrate the IPC mechanism
Message queues-oriented system calls.
4. Write UNIX system program or programs to demonstrate the socket-oriented
system calls around a small client/server example.
Lab Cycle -6
UNIX Systems Programming Exercises-2
1. Write a UNIX system program that will read disk data using block and raw
interface
2. Write a UNIX system program that will flood standard output with data
3. Write a UNIX system program that will contend for terminal input data
4. Write a UNIX system program that demonstrates the terminal driver in raw mode
– Reading 5-character bursts
5. Write a UNIX system program that demonstrates the terminal polling
6. Write UNIX system program or programs that demonstrates a general-purpose
system call ioctl for controlling character devices
7. Write UNIX system program or programs that demonstrate the STREAMS
mechanism provided by the System V as a general way to interface
communication drivers into the kernel (only Solaris provides native support for
STREAMS. A STREAMS subsystem is available for Linux, but you need to add
it yourself. It is not usually included by default)
8. Write UNIX system program or programs that demonstrate three functions poll,
pselect, and select which allow us to perform I/O multiplexing.
9. Write a UNIX system program that demonstrates nice system call
10. Write a UNIX system program that demonstrates alarm system call
11. Write a UNIX system program that demonstrates profil system call
12. Write UNIX system program or programs that demonstrates Times and Timersorie
nted
system calls

You might also like