Os lab manual


Published on

This Operating System lab manual is designed strictly according to BPUT Syllabus.Any suggestions or comments are well come at neelamani.samal@gmail.com

Published in: Education, Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Os lab manual

  1. 1. OPERATING STSTEM LAB MANUAL (For 6th sem CSE & IT) Strictly According To BPUT Syllabus Prepared By : Mr.Neelamani Samal Prepared By |Mr. Neelamani Samal 1
  2. 2. CONTENTExperiment Name of The Experiment Page No. NO. 1 Basic UNIX Commands. 3 2 UNIX Shell Programming. 22 3 Programs on process creation and synchronization, 39 inter process communication. 4 Programs on UNIX System calls. 45 Prepared By |Mr. Neelamani Samal 2
  3. 3. Laboratory Experiment 1 Objective :- To learn some basic UNIX commands to do system level programming. Software Required :- UNIX Operating System Commands:-Folder/Directory Commands and Options UNIX options & DOS filespec & Action filespec options Check pwd cd current Print Working Directory Return to users home folder cd cd / cd ~ Up one folder cd .. Make directory mkdir proj1 Remove empty directory rmdir /usr/sam rmdir or rd Remove directory -recursively rm -r rmdir /s (NT) deltree (Win 95) Prepared By |Mr. Neelamani Samal 3
  4. 4. File Listing Commands and Options UNIX options & DOS filespec & Action filespec options List directory tree -recursively ls -r tree List last access dates of files, with hidden ls -l -a files List files by reverse date ls -t -r *.* dir *.exe /o-d List files verbosely by size of file ls -l -s *.* dir *.* /v /os List files recursively including contents ls -R *.* dir *.* /s of other directories List number of lines in folder wc -l *.xtuml sed -n "$=" sed -n $= List files with x anywhere in the name ls | grep xFile Manipulation Commands and Options UNIX options & DOS filespec & Action filespec options Create new (blank) file touch afilename Copy old.file to new.file cp old.file copy old.file -p preserve file attributes (e.g. new.file new.* ownership and edit dates) -r copy recursively through directory structure -a archive, combines the flags -p - R and -d Move old.file (-i interactive flag mv -i old.file Copy old.file prompts before overwriting files) /tmp /tmp del old.file Remove file (-intention) rm -i sam.txt del sam.txt Compare two files and show diff comp differences fc Prepared By |Mr. Neelamani Samal 4
  5. 5. File Utilities DOS filespec & Action UNIX options & filespec options View a file vi file.txt edit file.txt Edit file pico myfile edit myfile Concatenate files cat file1 file2 to copy file2 standard output. >>file1 Counts -lines, -words, and - wc -l characters in a file Displays line-by-line differences diff between pairs of text files. calculator bc calendar for September, 1752 cal 9 1752 (when leap years began)Pattern Matching Pattern Example Position ? stands for any single character ls ?1 Position * stands for any number of ls 2* characters Specific [AB] stands for any number of ls [AB]1 would yield A1 characters characters and B1 Range of [A-Z] stands for letters from A characters thru Z Prepared By |Mr. Neelamani Samal 5
  6. 6. Files  ls --- lists your files ls -l --- lists your files in long format, which contains lots of useful information, e.g. the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified. ls -a --- lists all files, including the ones whose filenames begin in a dot, which you do not always want to see. There are many more options, for example to list files by size, by date, recursively etc.  more filename --- shows the first part of a file, just as much as will fit on one screen. Just hit the space bar to see more or q to quit. You can use /pattern to search for a pattern.  mv fname1 fname2 --- moves a file (i.e. gives it a different name, or moves it into a different directory (see below)  cp fname1 fname2 --- copies a file  rm filename --- removes a file. It is wise to use the option rm - i, which will ask you for confirmation before actually deleting anything. You can make this your default by making an alias in your .cshrc file.  diff fname1 fname2 --- compares files, and shows where they differ  wc fname --- tells you how many lines, words, and characters there are in a file  chmod opt fname --- lets you change the read, write, and execute permissions on your files. The default is that only you can look at them and change them, but you may sometimes want to change these permissions. For example, chmod o+r filename will make the file readable for everyone, and chmod o-rfilename will make it unreadable for others again. Note that for someone to be able to actually look at the file the directories it is in need to be at least executable. Prepared By |Mr. Neelamani Samal 6
  7. 7. DirectoriesDirectories, like folders on a Macintosh, are used to group files together in ahierarchical structure.  mkdir dirname --- make a new directory  cd dirname --- change directory. You basically go to another directory, and you will see the files in that directory when you do ls. You always start out in your home directory, and you can get back there by typing cd without arguments. cd .. will get you one level up from your current position. You dont have to walk along step by step - you can make big leaps or avoid walking around by specifying pathnames.  pwd --- tells you where you currently are.Finding things  ff --- find files anywhere on the system. This can be extremely useful if youve forgotten in which directory you put a file, but do remember the name. In fact, if you use ff -p you dont even need the full name, just the beginning. This can also be useful for finding other things on the system, e.g. documentation.  grep string fname(s) --- looks for the string in the files. This can be useful a lot of purposes, e.g. finding the right file among many, figuring out which is the right version of something, and even doing serious corpus work. grep comes in several varieties (grep, egrep, and fgrep) and has a lot of very flexible options. Check out the man pages if this sounds good to you. Prepared By |Mr. Neelamani Samal 7
  8. 8. About other people w --- Tells you whos logged in, and what theyre doing. Especially useful: the idle part. This allows you to see whether theyre actually sitting there typing away at their keyboards right at the moment. who --- Tells you whos logged on, and where theyre coming from. Useful if youre looking for someone whos actually physically in the same building as you, or in some other particular location. finger username --- gives you lots of information about that user, e.g. when they last read their mail and whether theyre logged in. Often people put other practical information, such as phone numbers and addresses, in a file called .plan. This information is also displayed by finger. last -1 username --- tells you when the user last logged on and off and from where. Without any options, last will give you a list of everyones logins. talk username --- lets you have a (typed) conversation with another user write username --- lets you exchange one-line messages with another user elm --- lets you send e-mail messages to people around the world (and, of course, read them). Its not the only mailer you can use, but the one we recommend. About your (electronic) self whoami --- returns your username. Sounds useless, but isnt. You may need to find out who it is who forgot to log out somewhere, and make sure *you* have logged out. passwd --- lets you change your password, which you should do regularly. ps -u yourusername --- lists your processes. Contains lots of information about them, including the process ID, this list will contain the processes you need to kill. kill PID --- kills (ends) the processes with the ID you gave. This works only for your own processes, of course. Get the ID by using ps. If the process doesnt die properly, use the option -9. But attempt without that option first, because it doesnt give the process a chance to finish possibly important business before dying. You may need to kill processes for example if your modem connection was interrupted and you didnt get logged out properly, which sometimes happens. Prepared By |Mr. Neelamani Samal 8
  9. 9.  quota -v --- show what your disk quota is (i.e. how much space you have to store files), how much youre actually using, and in case youve exceeded your quota (which youll be given an automatic warning about by the system) how much time you have left to sort them out (by deleting )  du filename --- shows the disk usage of the files and directories in filename (without argument the current directory is used). du -s gives only a total.  last yourusername --- lists your last logins.Login and authenticationlogin access computer; start interactive sessionlogout disconnect terminal session change local login password; you must set a strong password that ispasswd not easily guessedInformationdate show date and timehistory list of previously executed commandsman show online documentation by program namew, who who is on the system and what they are doingwhoami who is logged onto this terminalFile management Prepared By |Mr. Neelamani Samal 9
  10. 10. cat combine filescp copy filesls list files in a directory and their attributesmv change file name or directory locationrm remove filesln create another link (name) to a filechmod set file permissionsDisplay contents of filescat copy files to display devicemore show text file on display terminal with paging controlhead show first few lines of a file(s)tail show last few lines of a file; or reverse line ordervi full-featured screen editor for modifying text filespico simple screen editor for modifying text filesgrep display lines that match a patternlpr send file to printerdiff compare two files and show differencescmp compare two binary files and report if differentcomm compare two files; show common or unique lineswc count characters, words, and lines in a file Prepared By |Mr. Neelamani Samal 10
  11. 11. Directoriescd change to new directorymkdir create new directoryrmdir remove empty directory (you must remove files first)mv change name of directorypwd show current directoryDisksdf summarize free space on disk filesystemsdu show disk space used by files or directoriesControlling program execution for C-shell& run job in background^c kill job in foreground^z suspend job in foregroundfg restart suspended job in foregroundbg run suspended job in background; delimit commands on same line() group commands on same line! re-run earlier commands from history listjobs list current jobs Prepared By |Mr. Neelamani Samal 11
  12. 12. ps show process informationkill kill background job or previous processnice run program at lower priorityat run program at a later timecrontab run program at specified intervalslimit see or set resource limits for programsalias create alias name for program (normally used in .login file)sh, csh execute command fileControlling program input/output for C-shell| pipe output to input> redirect output to a storage file< redirect input from a storage file>> append redirected output to a storage filetee copy input to both file and next program in pipescript make file record of all terminal activityEditors and formatting utilitiessed programmable text editor for data streamsvi full-featured editor for character terminalspico very simple text editor Prepared By |Mr. Neelamani Samal 12
  13. 13. Printing (BSD based)lpr send file to print queuelpq examine status of files in print queuelprm remove a file from print queueenscript convert text files to PostScript format for printingStarting and Endinglogin: `Logging inssh: Connect to another machinelogout: `Logging outFile Managementemacs: `Using the emacs text editormkdir: `Creating a directorycd: `Changing your current working directoryls: `Finding out what files you havecp: `Making a copy of a filemv: `Changing the name of a filerm: `Getting rid of unwanted fileschmod: `Controlling access to your filescmp: Comparing two fileswc: Word, line, and character countcompress: Compress a fileCommunicatione-mail: `Sending and receiving electronic mailtalk: Talk to another user Prepared By |Mr. Neelamani Samal 13
  14. 14. write: Write messages to another usersftp: Secure file transfer protocolInformationman: Manual pagesquota -v: Finding out your available disk space quotaical: `Using the Ical personal organizerfinger: Getting information about a userpasswd: Changing your passwordwho: Finding out whos logged onPrintinglpr: `Printinglprm: Removing a print joblpq: Checking the print queuesJob controlps: `Finding your processeskill: `Killing a processnohup: Continuing a job after logoutnice: Changing the priority of a job&: `What is a background process?Cntrl-z: Suspending a processfg: `Resuming a suspended processBanner command.banner prints characters in a sort of ascii art poster, for example to print wait inbig letters. I will typebanner wait at unix command line or in my script. This is how it will look. Prepared By |Mr. Neelamani Samal 14
  15. 15. # # ## # ##### # # # # # # # # # # # # # ## # ###### # # ## ## # # # # # # # # # #Cal commandcal command will print the calander on current month by default. If you want toprint calander of august of 1965. Thats eightht month of 1965.cal 8 1965 will print following results. August 1965 S M Tu W Th F S 1 2 3 4 5 6 7 8 9 10 11 12 13 1415 16 17 18 19 20 2122 23 24 25 26 27 2829 30 31Clear commandclear command clears the screen and puts cursor at beginning of first line.Calendar commandcalendar command reads your calendar file and displays only lines with currentday.File Management commands.cat,cd, cp, file,head,tail, ln,ls,mkdir ,more,mv, pwd, rcp,rm, rmdir, wc.Pwd command.pwd command will print your home directory on screen, pwd means printworking directory. /u0/ssb/sandeepis output for the command when I use pwd in /u0/ssb/sandeep directory. Prepared By |Mr. Neelamani Samal 15
  16. 16. Ls commandls command is most widely used command and it displays the contents ofdirectory. options  ls will list all the files in your home directory, this command has many options.  ls -l will list all the file names, permissions, group, etc in long format.  ls -a will list all the files including hidden files that start with . .  ls -lt will list all files names based on the time of creation, newer files bring first.  ls -Fxwill list files and directory names will be followed by slash.  ls -Rwill lists all the files and files in the all the directories, recursively.  ls -R | more will list all the files and files in all the directories, one page at a time.Mkdir command.mkdir sandeep will create new directory, i.e. here sandeep directory is created.Cd command.cd sandeep will change directory from current directory to sandeep directory.Use pwd to check your current directory and ls to see if sandeep directory isthere or not.You can then use cd sandeep to change the directory to this new directory. will restore all files whose name contain "save" find . -depth -print | cpio -padm /mydir will move a directory tree.Chmod command.chmod command is used to change permissions on a file. Prepared By |Mr. Neelamani Samal 16
  17. 17. for example if I have a text file with calender in it calledcal.txt.initially when this file will be created the permissions for this file dependsupon umask set in your profile files. As you can see this file has666 or -rw-rw-rw attributes.ls -la cal.txt-rw-rw-rw- 1 ssb dxidev 135 Dec 3 16:14 cal.txtIn this line above I have -rw-rw-rw- meaning respectively that owner can readand write file, member of the owners group can read and write this fileand anyone else connected to this system can read and write this file., nextssb is owner of this file dxidev is the group of this file, there are 135 bytesin this file, this file was created on December 3 at time16:14 and at the endthere is name of this file. Learn to read these permissions in binary, like thisfor example Decimal 644 which is 110 100 100 in binary meand rw-r--r-- oruser can read,write this file, group can read only, everyone else can read only.Similarly, if permissions are 755 or 111 101 101 that means rwxr-xr-x or usercan read, write and execute, group can read and execute, everyone else can readand execute. All directories have d in front of permissions. So if you dont wantanyone to see your files or to do anything with it use chmod command andmake permissions so that only you can read and write to that file, i.e.chmod 600 filename.Date command.Date displays todays date, to use it type date at prompt.Sun Dec 7 14:23:08 EST 1997is similar to what you should see on screen.Df command.df command displays information about mounted filesystems. It reports thenumber of free disk blocks. Typically a Disk block is 512 bytes (or 1/2Kilobyte).syntax is Prepared By |Mr. Neelamani Samal 17
  18. 18. df options name Options  -b will print only the number of free blocks.  -e will print only the number of free files.  -f will report free blocks but not free inodes.  -F type will report on an umounted file system specified by type.  -k will print allocation in kilobytes.  -l will report only on local file systems.  -n will print only the file system name type, with no arguments it lists type of all filesystemsDu command.du command displays disk usage.Env command.env command displays all the variables.Finger command.finger command.PS commandps command is probably the most useful command for systems administrators.It reports information on active processes.ps options options.  -a Lists all processes in system except processes not attached to terminals.  -e Lists all processes in system.  -f Lists a full listing.  -j print process group ID and session ID. Prepared By |Mr. Neelamani Samal 18
  19. 19. Shutdown command.Shutdown command can only be executed by root. To gracefully bring down asystem, shutdown command is used. options.  -gn use a grace-period of n seconds (default is 60).  -ik tell the init command to place system in a state k. o s single-user state (default) o 0 shutdown for power-off. o 1 like s, but mount multi-user file systems. o 5 stop system, go to firmware mode. o 6 stop system then reboot.  -y suppress the default prompt for confirmation.Who commandwho command displays information about the current status of system.who options fileWho as default prints login names of users currently logged in. Options  -a use all options.  -b Report information about last reboot.  -d report expired processes.  -H print headings.  -p report previously spawned processes.  -u report terminal usage.date to display the current date and timekill to kill (or destroy) the process with a given pid (process identification Prepared By |Mr. Neelamani Samal 19
  20. 20. number) as argumentlogout to log out from the Unix systemman to get information on a Unix command; to look up the page in the online manual for that command man CC shows the pages of the Unix manual referring to the C++ compiler (CC) on the screen.nslookup to find the address of a given machine returns the name and address of the nslookup yourmach machine yourmach, along with the name and address of its server.passwd to change your current passwordprintenv to show the current environment settingps to list your current processes by their pid (process identification number)setenv to change an environment setting tells the Xserver that the Xterminal setenv DISPLAY yourmach:0 named yourmach is where any windows created are to be displayed. setenv PRINTER xxx makes xxx be the default printer for any lpr or enscript commands.source to reexecute a source shell script file re-executes your .login file source .login (normally executed when you log in); useful after making changes to the .login file (removing the need to exit and re-login);time to time the execution of a given command executes anyunixcommand and returns the time anyunixcommand user, system, and total time taken for the executionWho to list the users currently logged in to given machine; to find out who is logged in Prepared By |Mr. Neelamani Samal 20
  21. 21. Whoami to display login of user currently logged onto given terminal; to answer the question: "Who am I?"Other Language Commands:These commands help you to compile and debug programs in otherprogramming languages.cc to compile a C program compiles with optimization (-O) the C program cc -O acprog.c -o acprog -lm named acprog.c into the executable file named acprog, allowing the compilation to access the math library (-lm).CC to compile a C++ program compiles with optimization (-O) the C++ CC -O acprog.C -o acprog -lm program named acprog.C into the executable file named acprog, allowing the compilation to access the math library (-lm).dbx to debug a program runs the executable program named aprog that dbx aprog was compiled with a -g option in a debugging environment.lint to check the syntax of a C programf77 to compile a Fortran program compiles, without generating an executable file f77 -c fprog.f ftn1.f ftn2.f (-c), the Fortran program named fprog.f with the additional Fortran modules, ftn1.f and ftn2.f. compiles the Fortran program f77 -g -o debug anfprog.f called anfprog.f with a symbol table (-g) so that the executable file named debug can be used with the dbx command.Conclusion :- Prepared By |Mr. Neelamani Samal 21
  22. 22. Laboratory Experiment : 2Objective :-To learn the basic shell program and gain knowledge about the scripting language.Theory :- Shell scriptingLoopsMost languages have the concept of loops: If we want to repeat a task twenty times, we dontwant to have to type in the code twenty times, with maybe a slight change each time.As a result, we have for and while loops in the Bourne shell. This is somewhat fewer featuresthan other languages, but nobody claimed that shell programming has the power of C.For Loopsfor loops iterate through a set of values until the list is exhausted:for.sh#!/bin/shfor i in 1 2 3 4 5do echo "Looping ... number $i"doneTry this code and see what it does. Note that the values can be anything at all:for2.sh#!/bin/shfor i in hello 1 * 2 goodbyedo echo "Looping ... i is set to $i"done Prepared By |Mr. Neelamani Samal 22
  23. 23. is well worth trying. Make sure that you understand what is happening here. Try it withoutthe * and grasp the idea, then re-read the Wildcards section and try it again with the * in place.Try it also in different directories, and with the *surrounded by double quotes, and try it precededby a backslash (*)In case you dont have access to a shell at the moment (it is very useful to have a shell to handwhilst reading this tutorial), the results of the above two scripts are:Looping .... number 1Looping .... number 2Looping .... number 3Looping .... number 4Looping .... number 5and, for the second example:Looping ... i is set to helloLooping ... i is set to 1Looping ... i is set to (name of first file in current directory) ... etc ...Looping ... i is set to (name of last file in current directory)Looping ... i is set to 2Looping ... i is set to goodbyeSo, as you can see, for simply loops through whatever input it is given, until it runs out of input.While Loopswhile loops can be much more fun! (depending on your idea of fun, and how often you get outof the house... )while.sh#!/bin/shINPUT_STRING=hellowhile [ "$INPUT_STRING" != "bye" ]do echo "Please type something in (bye to quit)" read INPUT_STRING echo "You typed: $INPUT_STRING"done Prepared By |Mr. Neelamani Samal 23
  24. 24. TestTest is used by virtually every shell script written. It may not seem that way, because test is notoften called directly.test is more frequently called as [. [ is a symbolic link to test, just to makeshell programs more readable. If is also normally a shell builtin (which means that the shell itselfwill interpret [ as meaning test, even if your Unix environment is set up differently):$ type [[ is a shell builtin$ which [/usr/bin/[$ ls -l /usr/bin/[lrwxrwxrwx 1 root root 4 Mar 27 2000 /usr/bin/[ -> testThis means that [ is actually a program, just like ls and other programs, so it must besurrounded by spaces:if [$foo == "bar" ]will not work; it is interpreted as if test$foo == "bar" ], which is a ] without a beginning[. Put spaces around all your operators Ive highlighted the mandatory spaces with the wordSPACE - replace SPACE with an actual space; if there isnt a space there, it wont work:if SPACE [ SPACE "$foo" SPACE == SPACE "bar" SPACE ]Test is a simple but powerful comparison utility. For full details, run man test on your system,but here are some usages and typical examples.Test is most often invoked indirectly via the if and while statements. It is also the reason youwill come into difficulties if you create a program called test and try to run it, as this shell builtinwill be called instead of your program!The syntax for if...then...else... is:if [ ... ]then # if-codeelse # else-codefiNote that fi is if backwards! This is used again later with case and esac.Also, be aware of the syntax - the "if [ ... ]" and the "then" commands must be on different lines.Alternatively, the semicolon ";" can separate them: Prepared By |Mr. Neelamani Samal 24
  25. 25. if [ ... ]; then # do somethingfiYou can also use the elif, like this:if [ something ]; then echo "Something" elif [ something_else ]; then echo "Something else" else echo "None of the above"fiThis will echo "Something" if the [ something ] test succeeds, otherwise it will test [something_else ], and echo "Something else" if that succeeds. If all else fails, it will echo"None of the above".Try the following code snippet, before running it set the variable X to various values (try -1, 0, 1,hello, bye, etc). You can do this as follows$ X=5$ export X$ ./test.sh ... output of test.sh ...$ X=hello$ ./test.sh ... output of test.sh ...$ X=test.sh$ ./test.sh ... output of test.sh ...Then try it again, with $X as the name of an existing file, such as /etc/hosts.test.sh#!/bin/shif [ "$X" -lt "0" ]then echo "X is less than zero"fiif [ "$X" -gt "0" ]; then echo "X is more than zero"fi Prepared By |Mr. Neelamani Samal 25
  26. 26. [ "$X" -le "0" ] && echo "X is less than or equal to zero"[ "$X" -ge "0" ] && echo "X is more than or equal to zero"[ "$X" = "0" ] && echo "X is the string or number "0""[ "$X" = "hello" ] && echo "X matches the string "hello""[ "$X" != "hello" ] && echo "X is not the string "hello""[ -n "$X" ] && echo "X is of nonzero length"[ -f "$X" ] && echo "X is the path of a real file" || echo "No such file: $X"[ -x "$X" ] && echo "X is the path of an executable file"[ "$X" -nt "/etc/passwd" ] && echo "X is a file which is newer than /etc/passwd"Note that we can use the semicolon (;) to join two lines together. This is often done to save a bitof space in simple ifstatements. The backslash simply tells the shell that this is not the end ofthe line, but the two (or more) lines should be treated as one. This is useful for readability. It iscustomary to indent the following line.As we see from these examples, test can perform many tests on numbers, strings, andfilenames.Thanks to Aaron for pointing out that -a, -e (both meaning "file exists"), -S (file is a Socket), -nt (file is newer than), -ot(file is older than), -ef (paths refer to the same file) and -O (file isowned my user), are not available in the traditional Bourne shell (eg, /bin/sh on Solaris, AIX,HPUX, etc).There is a simpler way of writing if statements: The && and || commands give code to run ifthe result is true.#!/bin/sh[ $X -ne 0 ] && echo "X isnt zero" || echo "X is zero"[ -f $X ] && echo "X is a file" || echo "X is not a file"[ -n $X ] && echo "X is of non-zero length" || echo "X is of zero length" Prepared By |Mr. Neelamani Samal 26
  27. 27. This syntax is possible because there is a file (or shell-builtin) called [ which is linked to test.Be careful using this construct, though, as overuse can lead to very hard-to-read code.The if...then...else... structure is much more readable. Use of the [...] construct isrecommended for while loops and trivial sanity checks with which you do not want to overlydistract the reader.Note that when you set X to a non-numeric value, the first few comparisons result in themessage:test.sh: [: integer expression expected before -lttest.sh: [: integer expression expected before -gttest.sh: [: integer expression expected before -letest.sh: [: integer expression expected before -geThis is because the -lt, -gt, -le, -ge, comparisons are only designed for integers, and do not workon strings. The string comparisons, such as != will happily treat "5" as a string, but there is nosensible way of treating "Hello" as an integer, so the integer comparisons complain.If you want your shell script to behave more gracefully, you will have to check the contents of thevariable before you test it - maybe something like this:echo -en "Please guess the magic number: "read Xecho $X | grep "[^0-9]" > /dev/null 2>&1if [ "$?" -eq "0" ]; then # If the grep found something other than 0-9 # then its not an integer. echo "Sorry, wanted a number"else # The grep found only 0-9, so its an integer. # We can safely do a test on it. if [ "$X" == "7" ]; then echo "You entered the magic number!" fifiIn this way you can echo a more meaningful message to the user, and exit gracefully.The $? variable is explained inVariables - Part II, and grep is a complicated beast, so heregoes: grep [0-9] finds lines of text which contain digits (0-9) and possibly other characters, sothe caret (^) in grep [^0-9] finds only those lines which dont consist only of numbers. We canthen take the opposite (by acting on failure, not success). Okay? The >/dev/null 2>&1 directsany output or errors to the special "null" device, instead of going to the users screen.Many thanks to Paul Schermerhorn for correcting me - this page used to claim that grep -v[0-9] would work, but this is clearly far too simplistic.We can use test in while loops as follows: Prepared By |Mr. Neelamani Samal 27
  28. 28. test2.sh#!/bin/shX=0while [ -n "$X" ]do echo "Enter some text (RETURN to quit)" read X echo "You said: $X"doneThis code will keep asking for input until you hit RETURN (X is zero length). Thanks to JustinHeath for pointing out that the script didnt work - Id missed out the quotes around $X inthe while [ -n "$X" ]. Without those quotes, there is nothing to test when $X is empty.Alexander Weber has pointed out that running this script will end untidily:$ ./test2.shEnter some text (RETURN to quit)fredYou said: fredEnter some text (RETURN to quit)wilmaYou said: wilmaEnter some text (RETURN to quit)You said:$This can be tidied up with another test within the loop:#!/bin/shX=0while [ -n "$X" ]do echo "Enter some text (RETURN to quit)" read X if [ -n "$X" ]; then echo "You said: $X" fidoneNote also that Ive used two different syntaxes for if statements on this page. These are: Prepared By |Mr. Neelamani Samal 28
  29. 29. if [ "$X" -lt "0" ]then echo "X is less than zero"fi.......... and ........if [ ! -n "$X" ]; then echo "You said: $X"fiYou must have a break between the if statement and the then construct. This can be asemicolon or a newline, it doesnt matter which, but there must be one or the other betweenthe if and the then. It would be nice to just say:if [ ! -n "$X" ] echo "You said: $X"CaseThe case statement saves going through a whole set of if .. then .. else statements. Itssyntax is really quite simple:talk.sh#!/bin/shecho "Please talk to me ..."while :do read INPUT_STRING case $INPUT_STRING in hello) echo "Hello yourself!" ;; bye) echo "See you again!" break ;; *) echo "Sorry, I dont understand" ;; esacdoneechoecho "Thats all folks!" Prepared By |Mr. Neelamani Samal 29
  30. 30. Okay, so its not the best conversationalist in the world; its only an example!Try running it and check how it works...$ ./talk.shPlease talk to me ...helloHello yourself!What do you think of politics?Sorry, I dont understandbyeSee you again!Thats all folks!$The syntax is quite simple:The case line itself is always of the same format, and it means that we are testing the value ofthe variable INPUT_STRING. The options we understand are then listed and followed by a right bracket,as hello) and bye).This means that if INPUT_STRING matches hello then that section of code is executed, up tothe double semicolon.If INPUT_STRING matches bye then the goodbye message is printed and the loop exits. Notethat if we wanted to exit the script completely then we would use the command exit insteadof break.The third option here, the *), is the default catch-all condition; it is not required, but is oftenuseful for debugging purposes even if we think we know what values the test variable will have.The whole case statement is ended with esac (case backwards!) then we end the while loop witha done.Thats about as complicated as case conditions get, but they can be a very useful and powerfultool. They are often used to parse the parameters passed to a shell script, amongst other uses.foo=sunecho $fooshine # $fooshine is undefinedecho ${foo}shine # displays the word "sunshine"Thats not all, though - these fancy brackets have a another, much more powerful use. We candeal with issues of variables being undefined or null (in the shell, theres not much differencebetween undefined and null). Prepared By |Mr. Neelamani Samal 30
  31. 31. Using Default ValuesConsider the following code snippet which prompts the user for input, but accepts defaults:#!/bin/shecho -en "What is your name [ `whoami` ] "read mynameif [ -z "$myname" ]; then myname=`whoami`fiecho "Your name is : $myname"The "-en" to echo tells it not to add a linebreak. On some systems, you use a "c" at the end of theline, instead.This script runs like this:steve$ ./name.shWhat is your name [ steve ]Your name is : steve... or, with user input:steve$ ./name.shWhat is your name [ steve ] fooYour name is : fooThis could be done better using a shell variable feature. By using curly braces and the special ":-"usage, you can specify a default value to use if the variable is unset:echo -en "What is your name [ `whoami` ] "read mynameecho "Your name is : ${myname:-`whoami`}"This could be considered a special case - were using the output of the whoami command, whichprints your login name (UID). The more canonical example is to use fixed text, like this:echo "Your name is : ${myname:-John Doe}"As with other use of the backticks, `whoami` runs in a subshell, so any cd commands, orsetting any other variables, within the backticks, will not affect the currently-running shell.Using and Setting Default ValuesThere is another syntax, ":=", which sets the variable to the default if it is undefined:echo "Your name is : ${myname:=John Doe}"This technique means that any subsequent access to the $myname variable will always get avalue, either entered by the user, or "John Doe" otherwise. Prepared By |Mr. Neelamani Samal 31
  32. 32. FunctionsOne often-overlooked feature of Bourne shell script programming is that you can easily writefunctions for use within your script. This is generally done in one of two ways; with a simple script,the function is simply declared in the same file as it is called.However, when writing a suite of scripts, it is often easier to write a "library" of useful functions,and source that file at the start of the other scripts which use the functions. This will beshown later.The method is the same however it is done; we will primarily be using the first way here. Thesecond (library) method is basically the same, except that the command. ./library.shgoes at the start of the script.There could be some confusion about whether to call shell functions procedures or functions; thedefinition of a function is traditionally that is returns a single value, and does not output anything.A procedure, on the other hand, does not return a value, but may produce output. A shell functionmay do neither, either or both. It is generally accepted that in shell scripts they are calledfunctions.A function may return a value in one of four different ways:  Change the state of a variable or variables  Use the exit command to end the shell script  Use the return command to end the function, and return the supplied value to the calling section of the shell script  echo output to stdout, which will be caught by the caller just as c=`expr $a + $b` is caughtThis is rather like C, in that exit stops the program, and return returns control to the caller.The difference is that a shell function cannot change its parameters, though it can change globalparameters.A simple script using a function would look like this:function.sh#!/bin/sh# A simple script with a function...add_a_user(){ USER=$1 PASSWORD=$2 shift; shift; # Having shifted twice, the rest is now comments ... COMMENTS=$@ Prepared By |Mr. Neelamani Samal 32
  33. 33. echo "Adding user $USER ..." echo useradd -c "$COMMENTS" $USER echo passwd $USER $PASSWORD echo "Added user $USER ($COMMENTS) with pass $PASSWORD"}#### Main body of script starts here###echo "Start of script..."add_a_user bob letmein Bob Holness the presenteradd_a_user fred badpassword Fred Durst the singeradd_a_user bilko worsepassword Sgt. Bilko the role modelecho "End of script..."Line 4 identifies itself as a function declaration by ending in (). This is followed by {, andeverything following to the matching } is taken to be the code of that function.This code is not executed until the function is called. Functions are read in, but basically ignoreduntil they are actually called.Note that for this example the useradd and passwd commands have been prefixed with echo -this is a useful debugging technique to check that the right commands would be executed. It alsomeans that you can run the script without being root or adding dodgy user accounts to yoursystem!We have been used to the idea that a shell script is executed sequentially. This is not so withfunctions.In this case, the function add_a_user is read in and checked for syntax, but not executed until itis explicitly called.Execution starts with the echo statement "Start of script...". The next line, add_a_user bobletmein Bob Holness is recognised as a function call so the add_a_user function is enteredand starts executing with certain additions to the environment:$1=bob$2=letmein$3=Bob$4=Holness$5=the$6=presenterSo within that function, $1 is set to bob, regardless of what $1 may be set to outside of thefunction.So if we want to refer to the "original" $1 inside the function, we have to assign a name to it - Prepared By |Mr. Neelamani Samal 33
  34. 34. such as: A=$1 before we call the function. Then, within the function, we can refer to $A.We use the shift command again to get the $3 and onwards parameters into $@. The functionthen adds the user and sets their password. It echoes a comment to that effect, and returnscontrol to the next line of the main code.Scope of VariablesProgrammers used to other languages may be surprised at the scope rules for shell functions.Basically, there is no scoping, other than the parameters ($1, $2, $@, etc).Taking the following simple code segment:#!/bin/shmyfunc(){ echo "I was called as : $@" x=2}### Main script starts hereecho "Script was called with $@"x=1echo "x is $x"myfunc 1 2 3echo "x is $x"The script, when called as scope.sh a b c, gives the following output:Script was called with a b cx is 1I was called as : 1 2 3x is 2The $@ parameters are changed within the function to reflect how the function was called. Thevariable x, however, is effectively a global variable - myfunc changed it, and that change is stilleffective when control returns to the main script. Prepared By |Mr. Neelamani Samal 34
  35. 35. A function will be called in a sub-shell if its output is piped somewhere else - that is, "myfunc 12 3 | tee out.log" will still say "x is 1" the second time around. This is because a new shellprocess is called to pipe myfunc(). This can make debugging very frustrating; Astrid had ascript which suddenly failed when the "| tee" was added, and it is not immediately obvious whythis must be. The tee has to be started up before the function to the left of the pipe; with thesimple example of "ls | grep foo", then grep has to be started first, with its stdin then tiedto the stdout of ls once lsstarts. In the shell script, the shell has already been started beforewe even knew we were going to pipe through tee, so the operating system has to start tee, thenstart a new shell to call myfunc(). This is frustrating, but well worth being aware of.Functions cannot change the values they have been called with, either - this must be done bychanging the variables themselves, not the parameters as passed to the script.An example shows this more clearly:#!/bin/shmyfunc(){ echo "$1 is $1" echo "$2 is $2" # cannot change $1 - wed have to say: # 1="Goodbye Cruel" # which is not a valid syntax. However, we can # change $a: a="Goodbye Cruel"}### Main script starts herea=Hellob=Worldmyfunc $a $becho "a is $a"echo "b is $b"This rather cynical function changes $a, so the message "Hello World" becomes "Goodbye CruelWorld".RecursionFunctions can be recursive - heres a simple example of a factorial function: Prepared By |Mr. Neelamani Samal 35
  36. 36. factorial.sh#!/bin/shfactorial(){ if [ "$1" -gt "1" ]; then i=`expr $1 - 1` j=`factorial $i` k=`expr $1 * $j` echo $k else echo 1 fi}while :do echo "Enter a number:" read x factorial $xdonecommon.lib# common.lib# Note no #!/bin/sh as this should not spawn# an extra shell. Its not the end of the world# to have one, but clearer not to.#STD_MSG="About to rename some files..."rename(){ # expects to be called as: rename .txt .bak FROM=$1 TO=$2 for i in *$FROM do j=`basename $i $FROM` mv $i ${j}$TO Prepared By |Mr. Neelamani Samal 36
  37. 37. done}function2.sh#!/bin/sh# function2.sh. ./common.libecho $STD_MSGrename txt bakfunction3.sh#!/bin/sh# function3.sh. ./common.libecho $STD_MSGrename html html-bakHere we see two user shell scripts, function2.sh and function3.sh, each sourceing thecommon library file common.lib, and using variables and functions declared in that file.This is nothing too earth-shattering, just an example of how code reuse can be done in shellprogramming.Displaying and Printing Files:These commands allow you to see the contents of a file.Cat to display a text file or to concatenate files cat file1 displays contents of file1 on the screen (or window) without any screen breaks. displays contents of file1 followed by file2 on cat file1 file2 the screen (or window) without any screen breaks. creates file3 containing file1 followed cat file1 file2 > file3 by file2.Diff to show the differences between two files diff ABC DEF displays any lines in ABC or DEF that differ from each other.enscript to print a file with filename, date, and page number enscript -Pxxx -2rG ABC prints out the contents of file ABC on the printer Prepared By |Mr. Neelamani Samal 37
  38. 38. named xxx with two columns per page (-2), rotated 90 degrees (-r) so that it appears in a landscape format, with a gaudy heading (-G) as a shaded bar across the top that provides the filename (ABC), the creation date of that file, and the page number.Lpr to print a file lpr -Pxxx ABC DEF prints out the contents of the file ABC followed by the contents of the file DEF on printer xxx.more to display a file, screen by screen; to list the contents of a file to the terminal screen (or window) displays the two files ABC and DEF sequentially more ABC DEF on the screen. Hitting the space bar moves down one screen; the return key moves down one line.pr to paginate a file before printing it (to pretty it) breaks the contents of the files ABC and DEF into pages, puts a heading on the top of each file with pr ABC DEF the name of the file, the date and time, and a page number. The two files are numbered independently. The result goes to the screen. paginates the file ABC and sends the resultant file to be printed on xxx. This is an example of a Unix command that uses a pipe) (`|); that is, the pr ABC | lpr –Pxxx standard output of the first part of the command (before the pipe `|) is piped to (is treated as the standard input for) the second part. to perform a spelling check on a file;spell to list words found in the file that are not in the Unix spelling dictionary; Note: often lists words that are hyphenated (split across two lines)Conclusion :- Prepared By |Mr. Neelamani Samal 38
  39. 39. Laboratory Experiment No 3 :-Objective :-Learn the vi Editor and Programs on process creation.Theory:-The UNIX full screen editor `vi is a tightly designed editing system in whichalmost every letter has a function and the function is stronger for upper thanlower case. However, a letter and its actual function are usually closely related.It is important to remember that the `(Esc) escape key ends most functions anda `(Esc), (Esc) double application certainly ends the function with the ring of abell. The subcommand `u undoes the last function (presumably an error). Use`:q! (CR) to end with out saving, especially in hopeless situations. Use `:wq(CR) to resave and end {`ZZ also resaves and ends, but will not resave if thefile has been saved in another file and no further changes have been made}, or`:w (CR) to only resave. The character `: prompts the UNIX line editor `exwhich you can think of as being embedded in `vi. Some of the above critical`vi subcommands are repeated below with others. Most `vi subcommands arenot displayed when used and do not take a carriage return `(CR). The fact thatmost keys have a meaning both as single characters and as concatenations ofseveral characters has many benefits, but has disadvantages in that mistakes canturn out to be catastrophic. {Remember that `(Esc), (Esc), u key sequence!}{WARNING: `VI is disabled during an IBM Telnet session.} (Esc) : End a command; especially used with insert `i, append `a or replace R. (Esc), (Esc) : Ensured end of a command with bell; press the Escape-key twice; use it. u : Undoes last command; usually used after `(Esc) or `(Esc), (Esc); if undoing is worse then repeat `u again to undo the undoing. :set all (CR) : Display all vi options. Use this ex command when your initial vi session is poor. Customized options are placed in the `.exrc ex resource configuration profile. :w (CR) : Save or resave the default file being edited, but do not end. Prepared By |Mr. Neelamani Samal 39
  40. 40. :w [file] (CR) : Save into a new file [file], but do not end.:w! [file] (CR) : Save or resave into an existing file [file], but do not end.:q (CR) : Quit vi without saving, provided no changes have been madesince the last save.:q! (CR) : Quit vi without saving, living the file as it was in the last save.:wq (CR) : Save the default file being edited, and quit.ZZ : Save the edited file, provided not changes have been made since thelast save of the edited file to any file, and quit `vi. {Warning: if you justsaved the edited file into any other file, the file will NOT be resaved.`:wq (CR) is much safer to use.}h or j or k or l : The arrow keys, such that k = up ^ | h = left <-- --> right = l | v j = downeach take a number prefix that moves the cursor that many times.(CR) : moves cursor a line forward; `+ also does.-- : Moves cursor a line backward.[N] (CR) : Moves cursor [N] lines forwards.[N]-- : Moves cursor [N] lines backwards.Ctrl-f : Moves cursor a page forward.Ctrl-b : Moves cursor a page backward.Ctrl-d : Moves cursor a half page down.Ctrl-u : Moves cursor a half page up.[L]G : Go to line [L]. `1G moves the cursor to the beginning of the file(BOF). Prepared By |Mr. Neelamani Samal 40
  41. 41. G : Go to the last line just before the end of file (EOF) mark. `$G doesthe same thing.0 : Go to beginning of the line (BOL).^ : Go to beginning of the nonblank part of the line (BOL).~ : Got to first nonblank character on a line.$ : Go to end of the line (EOL).[N]| : Go to column [N] of the current line.% : Find the matching parenthesis./[string] (CR) : Find the next occurrence of `[string] forwards. Use `n torepeat, or `N to search backwards.?[string] (CR) : Find the next occurrence of` [string] backwards.n : Repeat last `/[string] (CR) or `?[string] (CR); think of the file asbeing wrapped around from end to beginning, so that when you return tothe start you know that you have found all occurrences.N : Repeat last `/[string] (CR) or `?[string] (CR), but in reverse.. : Repeat last change. This is best used along with the repeat search `nor `N.i[string](Esc) : Insert a string `[string] before current character at thecursor; the subcommand `i itself and other subcommands are notdisplayed; a `(CR) in the string during the insert is used to continueinput on additional lines; end with the escape key `(Esc) or `(Esc),(Esc).o[string](Esc) : Opens a new line below the current line for insertion ofstring `[string]; end with `(Esc) or `(Esc), (Esc); use for POWERTYPING input for an old or new file; `O[string](Esc) opens a new lineabove the current line for insertion.I[string](Esc) : Insert a string at the beginning of the current line (BOL),else is like insert `i;a `(CR) in the string during the insert is used tocontinue input on additional lines; end with `(Esc) or `(Esc), (Esc). Prepared By |Mr. Neelamani Samal 41
  42. 42. J : Joins next line to current line.a[string](Esc) : Appends a string `[string] following the currentcharacter at the cursor, else it works like insert `i; use `(CR) in the stringto continue input onto new lines; end with `(Esc); also use for POWERTYPING.A[string](Esc) : Appends a string `[string] at the end of a line (EOL),works like `i or `a; use `(CR) in the string to continue input onto newlines; end with `(Esc); also use for POWER TYPING.r[C](SPACE) : Replace a single character over the cursor by the singlecharacter [C]; finalize with the Space-bar.R[string](Esc) : Replace a string of characters by `[string] in until `(Esc)is typed to end.s[string](Esc) : Substitutes the string `[string] for the single character atthe cursor. The multiple form `[N]s[string](Esc) substitutes `[string] forthe `[N] characters starting at the cursor.x : Delete the current character at the cursor.d(SPACE) : Deletes a single character. `[N]d(SPACE) deletes `[N]characters.dd : Deletes the current line. `[N]dd deletes `[N] lines.D : Deletes from the cursor to the end of line (EOL).dw : Deletes the current word; `[N]dw deletes `[N] words.w : Move cursor to the beginning of the next word. `[N]w moves thecursor `[N] words forward. `[N]b moves it `[N] words backward. `[N]emoves it to the end of the word.[N]y(SPACE) : Yanks `[N] characters starting at the cursor and putsthem into the default buffer. `[N]yy yanks `[N] lines.p : Puts the current contents of the default buffer after the cursor ifcharacters or after the current line if lines. Helpful to use right after acharacter yank `y or a character delete `d or a line yank `yy or a linedelete `dd, along with a search `/[string](CR) or repeat search `n. and a Prepared By |Mr. Neelamani Samal 42
  43. 43. repeat change `.. `P puts the contents of the default buffer before the current line. "b[N]Y : Yank [N] lines starting with the current line to the buffer labeled b; the double quote {"} is used to avoid an id conflict with subcommand names; any letter other than `x can be used to name the buffer; safer than the line yank `yy because it is very easy to accidentally change the default buffer. "b[N]dd : Deletes [N] lines starting with the current line to the buffer labeled `b. "bp : Put back lines from the buffer labeled `b after or below the cursor; use after a yank or delete to a labeled buffer to move groups of lines from one location to another.Directory ManipulationPwd show the directory that you are in (present working directory)cd dir.1 change directory to dir.1mkdir dir.1 make new directory dir.1rmdir dir.1 remove EMPTY directory dir.1rm -r dir.1 remove directory dir.2 AND its contentscp -r dir.1 dir.2 copy dir.1 (and its contents) to dir.2mv file.1 dir.1 move file.1 to dir.1 show contents of current directory. Variations:Ls ls dir.1 shows contents of dir.1 ls -d dir.1 shows PRESENCE of dir.1du -sk dir.1 show sum of size (in kilobytes) of dir.1 and its contentstar -cvf dir.1.tar dir.1 store an image of dir.1 and its contents in file file.1Process Controlcommand1& execute command1 in backgroundps -ef print expanded list of all processeskill pid1 remove process pid1<control-c> interrupt current process<control-z> suspend current processjobs display background and suspended processes Prepared By |Mr. Neelamani Samal 43
  44. 44. /* Program to illustrate Inter Process Communication */#include <stdio.h>#include <types.h>#include <unistd.h>#include <stdlib.h>int main(){int pfd[2], i;pid_t mypid;if(pipe(pfd) < 0)perror(“Pipe Error”);if(!fork()){char data;printf(“Enter a Number…n”);scanf(“%d”, &data);write(pfd[1], &data, 1);mypid = getpid();printf(“I am process %dn”, mypid);printf(“My parent is process %dn”, getppid());printf(“Child Exiting…n”);exit(0);}else{char data1;read(pfd[0], &data1, 1);printf(“Received %d from child n”, data1);printf(“The odd numbers are… n”);for(i=1; i<=data1; i+=2){printf(“%5d”, i);sleep(2);}printf(“n Parent Exiting…n”);exit(0);}return(0);}Conclusion :- Prepared By |Mr. Neelamani Samal 44
  45. 45. Laboratory Experiment 4 :- Objective : Learn how to link C Language in UNIX and Programs on UNIX System calls cc -o run [file].c : Compiles source [file].c, using the standard C compiler and producing an executable named run. cc -c [file].c : Compiles source [file].c, using the standard C compiler `scc2.0 and producing an object file named [file].o.UNIX System Calls:- A system call is just what its name implies -- a request for the operating system to do something on behalf of the users program. The system calls are functions used in the kernel itself. To the programmer, the system call appears as a normal C function call. However since a system call executes code in the kernel, there must be a mechanism to change the mode of a process from user mode to kernel mode. The C compiler uses a predefined library of functions (the C library)that have the names of the system calls. The library functions typically invoke an instruction that changes the process execution mode to kernel mode and causes the kernel to start executing code for system calls. The instruction that causes the mode change is often referred to as an "operating system trap" which is a software generated interrupt .The library routines execute in user mode, but the system call interface is a special case of an interrupt handler. The library functions pass the kernel a unique number per system call in a machine dependent way --either as a parameter to the operating system trap, in a particular register, or on the stack -- and the kernel thus determines the specific system call the user is invoking. In handling the operating system trap, the kernel looks up the system call number in a table to find the address of the appropriate kernel routine that is the entry point for the system call and to find the number of parameters the system call expects. The kernel calculates the (user) address of the first parameter to the system call by adding (or subtracting, depending on the direction of stack growth) an offset to the user stack pointer, corresponding to the number of the parameters to the system call. Finally, it copies the user parameters to the "u area" and call the appropriate system call routine. After executing the code for the system call, the kernel determines whether there was an error. If so ,it adjusts register locations in the saved user register context ,typically setting the "carry" bit for the PS (processor status) register and copying the error number into register 0 location. If there were no errors in the execution of the system call, the kernel clears the "carry" bit in the PS register and copies the appropriate return values from the system call into the locations for registers 0 and 1 in the saved user register context. When the kernel returns from the operating system trap to user mode, it returns to the library instruction afterthe trap instruction. The library interprets the return values from the kernel and returns a value to the user program. UNIX system calls are used to manage the file system, control processes, and to provide inter process communication. The UNIX system interface Prepared By |Mr. Neelamani Samal 45
  46. 46. consists of about 80 system calls (as UNIX evolves this number willincrease).The following table lists about 40 of the more important system call: GENERAL CLASS SPECIFIC CLASS SYSTEM CALL File Structure Creating a Channel creat() Related Calls open() close() Input/Output read() write() Random Access lseek() Channel Duplication dup() Aliasing and Removing link() Files unlink() File Status stat() fstat() Access Control access() chmod() chown() umask() Device Control ioctl() --------------------------------------------------------------------- Process Related Process Creation and exec() Calls Termination fork() wait() exit() Process Owner and Group getuid()geteuid() getgid()getegid() Process Identity getpid()getppid() Process Control signal() kill() alarm() Change Working Directory chdir() ---------------------------------------------------------------------- Interprocess Pipelines pipe() Communication Messages msgget() msgsnd() msgrcv() msgctl() Semaphores semget() semop() Shared Memory shmget() shmat() shmdt() Prepared By |Mr. Neelamani Samal 46
  47. 47. /* errmsg1.c print all system error messages using "perror()" */ #include <stdio.h> int main() { int i; extern int errno, sys_nerr; for (i = 0; i < sys_nerr; ++i) { fprintf(stderr, "%3d",i); errno = i; perror(" "); } exit (0); }/* errmsg2.c print all system error messages using the global error messagetable. */ #include <stdio.h> int main() { int i; extern int sys_nerr; extern char *sys_errlist[]; fprintf(stderr,"Here are the current %d errormessages:nn",sys_nerr); for (i = 0; i < sys_nerr; ++i) fprintf(stderr,"%3d: %sn", i, sys_errlist[i]); } Conclusion :- Prepared By |Mr. Neelamani Samal 47