+ All Categories
Home > Documents > Operating Systems by Adnan Alam Khan

Operating Systems by Adnan Alam Khan

Date post: 04-Apr-2018
Category:
Upload: adnan-alam-khan
View: 219 times
Download: 0 times
Share this document with a friend

of 47

Transcript
  • 7/30/2019 Operating Systems by Adnan Alam Khan

    1/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

    Operating Systems

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    2/47

    Institute of Business & Technology (Operating Systems)

    LIST OF EXPERIMENT S

    Experiment No. Name of the Experiment

    1 Basic UNIX Commands

    2 UNIX Shell Programming

    3 Programs on process creation and synchronization, inter process communication.

    4 Programs on UNIX System calls.

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    3/47

    Institute of Business & Technology (Operating Systems)

    INDEX

    S.N

    O.

    NAME OF THE

    EXPERIMENT

    PERFORMED

    DATE

    SUBMITTED

    DATE

    PAGE

    NO.

    REMARKS

    __________________________SIGNATURE OF FACULTY

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    4/47

    Institute of Business & Technology (Operating Systems)

    EXPERIMENT NO. 01

    (I) Objective:-To learn some basic UNIX commands to do system level programming.

    (II) Software Required:-UNIX Operating System

    (III) Commands:-Folder/Directory Commands and Options.

    (IV) Folder Directory Command and Options: -

    (V) File listing Command and Options: -

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    5/47

    Institute of Business & Technology (Operating Systems)

    (VI) File Manipulation Command and Options: -

    (VII) File utilities:-

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    6/47

    Institute of Business & Technology (Operating Systems)

    (VIII)Pattern Matching:-

    (XI) Resource required: - Unix operating system in a PC.

    (X) Commands: -a. Files:-

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    7/47

    Institute of Business & Technology (Operating Systems)

    ls --- lists your files ls -l --- lists your files in 'long format', which contains lots of usefulinformation, e.g. the exact size of the file, who owns the file and who has the right to lookat it, and when it was last modified. ls -a --- lists all files, including the ones whosefilenames 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 adifferent directory (see below)

    cp fname1 fname2 --- copies a filerm filename --- removes a file. It is wise to use the option rm -i, which will ask you forconfirmation before actually deleting anything. You can make this your default by makingan alias in your .cshrc file.

    difffname1 fname2 --- compares files, and shows where they differwc fname --- tells you how many lines, words, and characters there are in a filechmod opt fname --- lets you change the read, write, and execute permissions onyour files. The default is that only you can look at them and change them, but you maysometimes want to change these permissions. For example, chmod o+r filename will makethe file readable for everyone, and chmod o-rfilename will make it unreadable for othersagain. Note that for someone to be able to actually look at the file the directories it is inneed to be at least executable.b.Directories:-Directories, like folders on a Macintosh, are used to group files together in a hierarchical

    structure.mkdir dirname --- make a new directorycd dirname --- change directory. You basically 'go' to another directory, and you will seethe 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 levelup from your current position. You don't have to walk along step by step - you can makebig 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 you've forgottenin which directory you put a file, but do remember the name. In fact, if you use ff -p youdon't even need the full name, just the beginning. This can also be useful for finding otherthings on the system, e.g. documentation.

    grep string fname(s) --- looks for the string in the files. This can be useful a lot ofpurposes, e.g. finding the right file among many, figuring out which is the right version ofsomething, and even doing serious corpus work. grep comes in several varieties (grep,

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    8/47

    Institute of Business & Technology (Operating Systems)

    egrep, and fgrep) and has a lot of very flexible options. Check out the man pages if thissounds good to you.

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    9/47

    Institute of Business & Technology (Operating Systems)

    c.About other people:-w --- Tells you who's logged in, and what they're doing. Especially useful: the 'idle' part.

    This allows you to see whether they're actually sitting there typing away at theirkeyboards right at the moment.

    who --- Tells you who's logged on, and where they're coming from. Useful if you'relooking for someone who's actually physically in the same building as you, or in someother particular location.

    finger username --- gives you lots of information about that user, e.g. when they lastread their mail and whether they're logged in. Often people put other practicalinformation, such as phone numbers and addresses, in a file called .plan. This informationis 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 everyone's logins.

    talkusername --- lets you have a (typed) conversation with another user

    write username --- lets you exchange one-line messages with another userelm --- lets you send e-mail messages to people around the world (and, of course, readthem). It's not the only mailer you can use, but the one we recommend. About your(electronic) self

    whoami --- returns your username. Sounds useless, but isn't. You may need to findout 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 ownprocesses, of course. Get the ID by using ps. If the process doesn't 'die' properly, use theoption -9. But attempt without that option first, because it doesn't give the process achance to finish possibly important business before dying. You may need to kill processesfor example if your modem connection was interrupted and you didn't get logged outproperly, which sometimes happens.

    quota -v --- show what your disk quota is (i.e. how much space you have to storefiles), how much you're actually using, and in case you've exceeded your quota (whichyou'll be given an automatic warning about by the system) how much time you have leftto sort them out (by deleting )

    du filename --- shows the disk usage of the files and directories in filename (withoutargument the current directory is used). du -s gives only a total.

    last yourusername --- lists your last logins.

    d. Login and authentication:-

    login access computer; start interactive session

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    10/47

    Institute of Business & Technology (Operating Systems)

    logout disconnect terminal sessionpasswd change local login password; you must set a strong password that is noteasily guessed

    e. Information:-

    date 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 doing whoami who is logged ontothis terminalf. File management

    cat combine files

    cp copy filesls list files in a directory and their attributesmv change file name or directory locationrm remove files ln create another link (name) to a filechmod set file permissionsg. Display contents of files

    cat 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 printerdiffcompare two files and show differences

    cmp compare two binary files and report if differentcomm compare two files; show common or unique lineswc count characters, words, and lines in a fileh.Directories

    cd change to new directory

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    11/47

    Institute of Business & Technology (Operating Systems)

    mkdir create new directoryrmdir remove empty directory (you must remove files first)mv change name of directorypwd show current directoryi.Disks

    dfsummarize free space on disk filesystemsdu show disk space used by files or directories

    j.Controlling program execution for C-shell

    & run job in background^c kill job in foreground^z suspend job in foreground

    fg 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 jobsps show process information

    kill 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 filek.Controlling 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 pipe

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    12/47

    Institute of Business & Technology (Operating Systems)

    script make file record of all terminal activity

    l.Editors and formatting utilities

    sedprogrammable text editor for data streams

    vi full-featured editor for character terminalspico very simple text editor

    j.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 printing

    (XI) Starting and Ending: -

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    13/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    14/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    15/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    16/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    17/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    18/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    19/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    20/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    21/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    22/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    23/47

    Institute of Business & Technology (Operating Systems)

    EXPERIMENT NO. 02

    Objective :-To learn the basic shell program and gain knowledge about the scripting language.Theory :-Shell scripting in Unix.Loops :-Most languages have the concept of loops: If we want to repeat a task twenty times, wedon't want to have to type in the code twenty times, with maybe a slight change eachtime. As a result, we have for and while loops in the Bourne shell. This is somewhat fewerfeatures than other languages, but nobody claimed that shell programming has the powerof C.For Loops:-for loops iterate through a set of values until the list is exhausted:

    Try this code and see what it does. Note that the values can be anything at all:

    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 * inplace. Try it also in different directories, and with the *surrounded by double quotes, andtry it preceded by a backslash (\*)In case you don't have access to a shell at the moment (it is very useful to have a shell tohand whilst reading this tutorial), the results of the above two scripts are:

    and, for the second example:

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    24/47

    Institute of Business & Technology (Operating Systems)

    So, as you can see, for simply loops through whatever input it is given, until it runs out ofinput.While Loops:-while loops can be much more fun! (depending on your idea of fun, and how often you getout of the house... )

    Test:-Test is used by virtually every shell script written. It may not seem that way, because testis not often called directly.test is more frequently called as [. [ is a symbolic link to test,

    just to make shell programs more readable. If is also normally a shell builtin (which meansthat the shell itself will interpret [ as meaning test, even if your Unix environment is set updifferently):

    This means that '[' is actually a program, just like ls and other programs, so it must besurrounded by spaces:

    will not work; it is interpreted as if test$foo == "bar" ], which is a ']' without a beginning'['. Put spaces around all your operators I've highlighted the mandatory spaces with the

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    25/47

    Institute of Business & Technology (Operating Systems)

    word 'SPACE' - replace 'SPACE' with an actual space; if there isn't a space there, it won'twork:

    Test is a simple but powerful comparison utility. For full details, run man test on yoursystem, but here are some usages and typical examples.Test is most often invokedindirectly via the if and while statements. It is also the reason you will come into difficultiesif you create a program called test and try to run it, as this shell builtin will be calledinstead of your program! The syntax for if...then...else... is:

    Note that fi is if backwards! This is used again later with case and esac. Also, be aware ofthe syntax - the "if [ ... ]" and the "then" commands must be on different lines.Alternatively, the semicolon ";" can separate them:

    You can also use the elif, like this:

    This 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

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    26/47

    Institute of Business & Technology (Operating Systems)

    Then try it again, with $X as the name of an existing file, such as /etc/hosts.

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    27/47

    Institute of Business & Technology (Operating Systems)

    Note that we can use the semicolon (;) to join two lines together. This is often done to savea bit of space in simple ifstatements. The backslash simply tells the shell that this is notthe end of the line, but the two (or more) lines should be treated as one. This is useful forreadability. It is customary to indent the following line. As we see from these examples,

    test can perform many tests on numbers, strings, and filenames.Thanks to Aaron for pointing out that -a, -e (both meaning "file exists"), -S (file is aSocket), -nt (file is newer than), -ot(file is older than), -ef (paths refer to the same file) and-O (file is owned my user), are not available in the traditional Bourne shell (eg, /bin/sh onSolaris, AIX, HPUX, etc).

    There is a simpler way of writing if statements: The && and || commands give code to runif the result is true.

    This syntax is possible because there is a file (or shell-builtin) called [ which is linked totest. Be careful using this construct, though, as overuse can lead to very hard-to-readcode. 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 tooverly distract the reader.

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    28/47

    Institute of Business & Technology (Operating Systems)

    Note that when you set X to a non-numeric value, the first few comparisons result in themessage:

    This is because the -lt, -gt, -le, -ge, comparisons are only designed for integers, and do notwork on strings. The string comparisons, such as != will happily treat "5" as a string, butthere is no sensible way of treating "Hello" as an integer, so the integer comparisonscomplain. If you want your shell script to behave more gracefully, you will have to checkthe contents of the variable before you test it - maybe something like this:

    In 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 here goes: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 don't consist only of numbers. Wecan then take the opposite (by acting on failure, not success). Okay? The >/dev/null 2>&1directs any output or errors to the special "null" device, instead of going to the user's

    screen. Many thanks to Paul Schermerhorn for correcting me - this page used to claim thatgrep -v [0-9] would work, but this is clearly far too simplistic.We can use test in while loops as follows:

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    29/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    30/47

    Institute of Business & Technology (Operating Systems)

    This code will keep asking for input until you hit RETURN (X is zero length). Thanks toJustin Heath for pointing out that the script didn't work - I'd missed out the quotes around$X in the 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:

    This can be tidied up with another test within the loop:

    Note also that I've used two different syntaxes for if statements on this page. These are:

    You must have a break between the if statement and the then construct. This can be a

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    31/47

    Institute of Business & Technology (Operating Systems)

    semicolon or a newline, it doesn't matter which, but there must be one or the otherbetween the if and the then. It would be nice to just say:

    Case:-The case statement saves going through a whole set of if .. then .. else statements. Itssyntax is really quite simple:

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    32/47

    Institute of Business & Technology (Operating Systems)

    Okay, so it's not the best conversationalist in the world; it's only an example!Try running it and check how it works...

    The syntax is quite simple: The case line itself is always of the same format, and it meansthat we are testing the value of the variable INPUT_STRING.

    The options we understand are then listed and followed by a right bracket, as hello) andbye). This means that if INPUT_STRING matches hello then that section of code isexecuted, up to the double semicolon. If INPUT_STRING matches bye then the goodbyemessage is printed and the loop exits. Note that if we wanted to exit the script completelythen we would use the command exit instead of break. The third option here, the *), is the

    default catch-all condition; it is not required, but is often useful for debugging purposeseven 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 whileloop with a done.

    That's about as complicated as case conditions get, but they can be a very useful andpowerful tool. They are often used to parse the parameters passed to a shell script,amongst other uses.

    That's not all, though - these fancy brackets have a another, much more powerful use. Wecan deal with issues of variables being undefined or null (in the shell, there's not muchdifference between undefined and null).

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    33/47

    Institute of Business & Technology (Operating Systems)

    Functions:-One often-overlooked feature of Bourne shell script programming is that you can easilywrite functions for use within your script. This is generally done in one of two ways; with asimple script, the function is simply declared in the same file as it is called. However, whenwriting a suite of scripts, it is often easier to write a "library" of useful functions, andsource that file at the start of the other scripts which use the functions. This will be shownlater. The method is the same however it is done; we will primarily be using the first wayhere. The second (library) method is basically the same, except that the command

    goes at the start of the script.There could be some confusion about whether to call shell functions procedures orfunctions; the definition of a function is traditionally that is returns a single value, and doesnot output anything. A procedure, on the other hand, does not return a value, but mayproduce output. A shell function may do neither, either or both. It is generally acceptedthat in shell scripts they are called functions.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` iscaught

    This 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 changeglobal parameters.A simple script using a function would look like this:

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    34/47

    Institute of Business & Technology (Operating Systems)

    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 codeis 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 withecho - this is a useful debugging technique to check that the right commands would beexecuted. It also means that you can run the script without being root or adding dodgyuser accounts to your system!We have been used to the idea that a shell script is executed sequentially. This is not sowith functions. In this case, the function add_a_user is read in and checked for syntax, but

    not executed until it is explicitly called. Execution starts with the echo statement "Start ofscript...". The next line, add_a_user bob letmein Bob Holness is recognized as a functioncall so the add_a_user function is entered and starts executing with certain additions tothe environment:

    So 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 aname to it - such as: A=$1 before we call the function. Then, within the function, we canrefer to $A. We use the shift command again to get the $3 and onwards parameters into$@. The function then adds the user and sets their password. It echoes a comment to thateffect, and returns control to the next line of the main code.Scope of Variables:-

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    35/47

    Institute of Business & Technology (Operating Systems)

    Programmers used to other languages may be surprised at the scope rules for shellfunctions. Basically, there is no scoping, other than the parameters ($1, $2, $@, etc).

    Taking the following simple code segment:

    The script, when called as scope.sh a b c, gives the following output:

    The $@ parameters are changed within the function to reflect how the function was called.The variable x, however, is effectively a global variable - myfunc changed it, and thatchange is still effective when control returns to the main script.A function will be called ina sub-shell if its output is piped somewhere else - that is, "myfunc 1 2 3 | tee out.log" willstill say "x is 1" the second time around. This is because a new shell process is called topipe myfunc(). This can make debugging very frustrating; Astrid had a script whichsuddenly failed when the "| tee" was added, and it is not immediately obvious why thismust 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 tied

    to the stdout of ls once lsstarts. In the shell script, the shell has already been startedbefore we even knew we were going to pipe through tee, so the operating system has tostart tee, then start a new shell to call myfunc(). This is frustrating, but well worth beingaware of.Functions cannot change the values they have been called with, either - this must be doneby changing the variables themselves, not the parameters as passed to the script. Anexample shows this more clearly:

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    36/47

    Institute of Business & Technology (Operating Systems)

    This rather cynical function changes $a, so the message "Hello World" becomes "GoodbyeCruel World".

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    37/47

    Institute of Business & Technology (Operating Systems)

    Recursion:-Functions can be recursive - here's a simple example of a factorial function:

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    38/47

    Institute of Business & Technology (Operating Systems)

    Here 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 inshell programming.

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    39/47

    Institute of Business & Technology (Operating Systems)

    Displaying and Printing Files:-These commands allow you to see the contents of a file.Cat to display a text file or to concatenate filescat file1 displays contents of file1 on the screen (or window) without any screenbreaks.cat file1 file2displays contents of file1 followed by file2 on the screen (or window) withoutany screen breaks.cat file1 file2 > file3 creates file3 containing file1 followed by file2.Diff to show the differences between two filesdiff 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 printernamed xxx with two columns per page (-2), rotated 90 degrees (-r) so that itappears in a landscape format, with a gaudy heading (-G) as a shaded baracross the top that provides the filename (ABC), the creation date of that file,and the page number.

    Lpr to print a filelpr -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 terminalscreen (or window)

    more ABC DEF displays the two files ABC and DEF sequentially on thescreen. Hitting the space bar moves down one screen; thereturn key moves down one line.

    Pr to paginate a file before printing it (to pretty it)pr ABC DEF breaks the contents of the files ABC and DEF into pages, puts a heading on

    the top of each file with the name of the file, the date and time, and a pagenumber. The two files are numbered independently. The result goes to thescreen.

    pr ABC | lpr Pxxxpaginates the file ABC and sends the resultant file to be printed on xxx. Thisis an example of a Unix command that uses a pipe) (`|'); that is, the standardoutput of the first part of the command (before the pipe `|') is piped to (istreated as the standard input for) the second part.

    Spell to perform a spelling check on a file; to list words found in the file that are not in theUnix spelling dictionary; Note: often lists words that are hyphenated (splitacross two lines)

    Conclusion:-

    __________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________ .

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    40/47

    Institute of Business & Technology (Operating Systems)

    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 closelyrelated. It is important to remember that the `(Esc)' escape key ends mostfunctions and a `(Esc), (Esc)' double application certainly ends the functionwith the ring of a bell. The subcommand `u' undoes the last function(presumably an error). Use `:q! (CR)' to end with out saving, especially inhopeless situations. Use `:wq (CR)' to resave and end {`ZZ' also resaves andends, but will not resave if the file has been saved in another file and nofurther changes have been made}, or `:w (CR)' to only resave. The character`:' prompts the UNIX line editor `ex' which you can think of as beingembedded in `vi'. Some of the above critical `vi' subcommands are repeated

    below with others. Most `vi' subcommands are not displayed when used anddo not take a carriage return `(CR)'. The fact that most keys have a meaningboth as single characters and as concatenations of several characters hasmany benefits, but has disadvantages in that mistakes can turn out to becatastrophic. {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-keytwice; use it.u : Undoes last command; usually used after `(Esc)' or `(Esc), (Esc)'; ifundoing is worse then repeat `u' again to undo the undoing.

    :set all (CR) : Display all vi options. Use this ex command when your initial visession is poor. Customized options are placed in the `.exrc' ex resourceconfiguration profile.:w (CR) : Save or resave the default file being edited, but do not end.: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 made since

    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 just

    saved 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|

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    41/47

    Institute of Business & Technology (Operating Systems)

    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).G : Go to the last line just before the end of file (EOF) mark. `$G' does the

    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 as beingwrapped around from end to beginning, so that when you return to the startyou 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 `n' or

    `N'.i[string](Esc) : Insert a string `[string]' before current character at the cursor;the subcommand `i' itself and other subcommands are not displayed; a `(CR)'in the string during the insert is used to continue input 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 of string`[string]'; end with `(Esc)' or `(Esc), (Esc)'; use for POWER TYPING input for anold or new file; `O[string](Esc)' opens a new line above the current line forinsertion.I[string](Esc) : Insert a string at the beginning of the current line (BOL), else islike insert `i';a `(CR)' in the string during the insert is used to continue inputon additional lines; end with `(Esc)' or `(Esc), (Esc)'.

    J : Joins next line to current line.a[string](Esc) : Appends a string `[string]' following the current character atthe cursor, else it works like insert `i'; use `(CR)' in the string to continueinput onto new lines; end with `(Esc)'; also use for POWER TYPING.A[string](Esc) : Appends a string `[string]' at the end of a line (EOL), workslike `i' or `a'; use `(CR)' in the string to continue input onto new lines; endwith `(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.

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    42/47

    Institute of Business & Technology (Operating Systems)

    R[string](Esc) : Replace a string of characters by `[string]' in until `(Esc)' istyped to end.s[string](Esc) : Substitutes the string `[string]' for the single character at thecursor. The multiple form `[N]s[string](Esc)' substitutes `[string]' for the `[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 the cursor`[N]' words forward. `[N]b' moves it `[N]' words backward. `[N]e' moves it tothe end of the word.[N]y(SPACE) : Yanks `[N]' characters starting at the cursor and puts them intothe 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 line delete`dd', along with a search `/[string](CR)' or repeat search `n'. and arepeat change `.'. `P' puts the contents of the default buffer before thecurrent 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 lineyank `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; useafter a yank or delete to a labeled buffer to move groups of lines from onelocation to another.

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    43/47

    Institute of Business & Technology (Operating Systems)

    /* Program to illustrate Inter Process Communication */#include #include #include

    #include int main(){int pfd[2], i;pid_t mypid;if(pipe(pfd) < 0)perror(Pipe Error);if(!fork())

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    44/47

    Institute of Business & Technology (Operating Systems)

    {char data;printf(Enter a Number\n);scanf(%d, &data);write(pfd[1], &data, 1);mypid = getpid();printf(I am process %d\n, mypid);printf(My parent is process %d\n, 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

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    45/47

    Institute of Business & Technology (Operating Systems)

    Laboratory Experiment 4 :-

    Objective :Learn how to link C Language in UNIX and Programs on UNIX System callscc -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' andproducing 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 dosomething on behalf of the user's program. The system calls are functions used in thekernel 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 tochange the mode of a process from user mode to kernel mode. The C compiler uses apredefined library of functions (the C library)that have the names of the system calls. Thelibrary functions typically invoke an instruction that changes the process execution modeto 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 thesystem call interface is a special case of an interrupt handler. The library functions passthe kernel a unique number per system call in a machine dependent way --either as aparameter to the operating system trap, in a particular register, or on the stack -- and thekernel thus determines the specific system call the user is invoking. In handling theoperating system trap, the kernel looks up the system call number in a table to find theaddress of the appropriate kernel routine that is the entry point for the system call and tofind 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 onthe direction of stack growth) an offset to the user stack pointer, corresponding to thenumber 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 thesystem call, the kernel determines whether there was an error. If so ,it adjusts registerlocations 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 therewere no errors in the execution of the system call, the kernel clears the "carry" bit in thePS register and copies the appropriate return values from the system call into the locationsfor registers 0 and 1 in the saved user register context. When the kernel returns from theoperating system trap to user mode, it returns to the library instruction afterthe trapinstruction. The library interprets the return values from the kernel and returns a value tothe user program. UNIX system calls are used to manage the file system, controlprocesses, and to provide inter process communication. The UNIX system interfaceconsists of about 80 system calls (as UNIX evolves this number willincrease).The following

    table lists about 40 of the more important system call:

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    46/47

    Institute of Business & Technology (Operating Systems)

    Developed by:Adnan AlamKhan([email protected])

    Department of Computer Science & Information Technology

  • 7/30/2019 Operating Systems by Adnan Alam Khan

    47/47

    Institute of Business & Technology (Operating Systems)

    Conclusion:-_____________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________ .


Recommended