Linux 56 Assignment

  • Upload
    rks

  • View
    220

  • Download
    0

Embed Size (px)

Citation preview

  • 8/10/2019 Linux 56 Assignment

    1/32

    http://www.cs.cmu.edu/~213/oldexams/ MCQ

    http://www.cs.toronto.edu/~reid/csc209/tests/

    1) Write a Linux shell script (/bin/bash) which has two command line parameters, a username and a filename. The script should determine the number of times the user with that username is logged into thesystem and write that number to the gi en file. !f the file already exists, the script should output an error message. "ome commands you might li#e to use are $grep%, $wc% and $who%.

    "olution&

    ' /bin/sh

    if *' +e - then

    username0*1

    filename0*-

    if +f *filename then

    echo *filename already exists2

    else

    set 3who 4 grep 56*username 5 4 wc3

    echo *1 7*filename

    fi

    else

    echo 8sage& *9 :username7 :filename72

    fi

    -) ;i e an example of a Linux file management system call and describe what it does.

    Solution: Example: read(fd, buffer, nbytes)It reads a certain number of data bytes from a file to a buffer and returns the number of bytes read or anerror code

    on?t forget to chec# for error conditions.

    'include :stdio.h7

    'include :sys/types.h7

    main()

    @

    http://www.cs.cmu.edu/~213/oldexams/http://www.cs.toronto.edu/~reid/csc209/tests/http://www.cs.cmu.edu/~213/oldexams/http://www.cs.toronto.edu/~reid/csc209/tests/
  • 8/10/2019 Linux 56 Assignment

    2/32

    pidAt child

    int status

    B!LC Dfp

    child0for#()

    if (child00+1)

    printf(5Crror creating child process5)

    else

    if (child009) @

    fp 0 fopen(5abc5, 5w5)

    if (fp00E8LL) printf(5Crror creating file5)

    else

    fclose(fp)

    F

    else @

    child0wait(Gstatus)

    if (child00+1) printf(5Crror waiting for child process5)

    else printf(5HldIn5, (long)child)

    F

    }

    J) Write an explanatory note on en ironment ariables. Klso write a = program that outputs the contents of its en ironment list.

    Kns& The en ironment list is an array of character pointers, with each pointer containing the address of a null+terminated = string. The address of the array of pointers is contained in the global ariable

    environ &

    extern char DDen iron

    We?ll call environ the environment pointer , the array of pointers the en ironment list, and thestrings they point to the environment strings .

    y con ention, the en ironment consists of

  • 8/10/2019 Linux 56 Assignment

    3/32

  • 8/10/2019 Linux 56 Assignment

    4/32

    1N) Turn off interrupts.

    1P) Xodify entries in de ice+status table.

    1Q) "witch from user to #ernel mode.

    1S) Kccess !/ de ice.

    Knswer& The following operations need to be pri ileged& "et alue of timer, clear memory, turn off interrupts,modify entries in de ice+status table, access !/ de ice. The rest can be performed in user mode.

    1U) What is the purpose of system callsO

    Knswer& "ystem calls allow user+le el processes to re uest ser ices of the operating system.

    -9) What are the fi e maYor acti ities of an operating system in regard to process managementO

    Knswer&

    a. The creation and deletion of both user and system processes

    b. The suspension and resumption of processes

    c. The pro ision of mechanisms for process synchroniZation

    d. The pro ision of mechanisms for process communication

    e. The pro ision of mechanisms for deadloc# handling

    -1) What are the three maYor acti ities of an operating system in regard to memory managementO

    Knswer&

    a. [eep trac# of which parts of memory are currently being used and by whom.

    b. >ecide which processes are to be loaded into memory when memory space becomes a ailable.

    c. Kllocate and de+allocate memory space as needed

    --) What are the three maYor acti ities of an operating system in regard to secondary+storage managementO

    Knswer&

    \ Bree+space management.

    \ "torage allocation.

    \ >is# scheduling

    -

  • 8/10/2019 Linux 56 Assignment

    5/32

    -J) What system calls ha e to be executed by a command interpreter or shell in order to start a newprocessO

    Knswer& !n 8nix systems, a for# system call followed by an exec system call need to be performed tostart a new process. The for# call clones the currently executing process, while the exec call o erlays anew process based on a different executable o er the calling process.

    -N) What is the purpose of system programsO

    Knswer& "ystem programs can be thought of as bundles of useful system calls. They pro ide basicfunctionality to users so that users do not need to write their own programs to sol e common problems.

    -P) What is the main ad antage of the layered approach to system designO What are the disad antages of using the layered approachO

    Knswer& Ks in all cases of modular design, designing an operating system in a modular way has se eralad antages. The system is easier to debug and modify because changes affect only limited sections of thesystem rather than touching all sections of the operating system. !nformation is #ept only where it is neededand is accessible only within a defined and restricted area, so any bugs affecting that data must be limited toa specific module or layer.

    -Q) List fi e ser ices pro ided by an operating system. Cxplain how each pro ides con enience to the users.Cxplain also in which cases it would be impossible for user+le el programs to pro ide these ser ices.

    Knswer&

    -S) Vrogram execution . The operating system loads the contents (or sections) of a file into memory andbegins its execution. K user+le el program could not be trusted to properly allocate =V8 time.

    -U) !/ operations . >is#s, tapes, serial lines, and other de ices must be communicated with at a ery lowle el. The user need only specify the de ice and the operation to perform on it, while the systemcon erts that re uest into de ice+ or controller+specific commands. 8ser+le el programs cannot betrusted to access only de ices they should ha e access to and to access them only when they are

    otherwise unused.

    eleting afile re uires remo ing the name file information and freeing the allocated bloc#s. Vrotections must alsobe chec#ed to assure proper file access. 8ser programs could neither ensure adherence to protectionmethods nor be trusted to allocate only free bloc#s and de+allocate bloc#s on file deletion.

  • 8/10/2019 Linux 56 Assignment

    6/32

  • 8/10/2019 Linux 56 Assignment

    7/32

    .

  • 8/10/2019 Linux 56 Assignment

    8/32

    F

    else if (pid1) @ // first child, pipe command output

    close(fd 9 )

    dup-(fd 1 , 1)

    close(fd 1 )

    exec p(arg 1 , arg M1)

    F

    else @ // second child, sort from pipe

    close(fd 1 )

    dup-(fd 9 , 9)

    close(fd 9 )

    execlp(5sort5, 5sort5, 9)

    F

    F

    isplay the path.

    J-) =ompile fool.c in the bac#ground with standard output and standard error discarded.

    J

  • 8/10/2019 Linux 56 Assignment

    9/32

    T The processor must be in kernel mode to set segment registers.T A disk drive may interrupt a user process before its time slice is up.T A segmentation fault will put the processor in kernel mode.

    !rocesses owned by root always run in kernel mode.T The boot block contains code which is run when the computer is turned on

    A "ombie process is removed when it receives a S#$%&'( signal.T %alling sleep)* may raise a process+s priority.T The ,ob of the -- is to translate logical addresses to physical.

    The ,ob of the page daemon is to load pages into memory.T fork)* sets the copy/on/write flag of a processor+s pages.

    JP) Write a = program to run 5cmp file1 file- 7 /de /null5 using Linux system calls and then print the exitstatus of cmp to the screen. !f status 0 9 then files are same otherwise they are different.

    // KE"WC

    'include :stdio.h7

    'include :fcntl.h7

    'include :unistd.h7

    'include :sys/wait.h7

    main() @

    int fd, status

    if (for#()) @ // parent

    wait(Gstatus)

    printf(5status 0 HdIn5, status77S)

    F

    else @ // child

    fd0open(5/de /null5, AW EL_)

    dup-(fd, 1)

    execlp(5cmp5, 5cmp5, 5file15, 5file-5, E8LL)

    F

    F

    JQ) What - things does a system call usually do in case of an errorO

    KE"WC & set errno and return +1

    JS) Row many processes are created when the following program is runO

    main() @

  • 8/10/2019 Linux 56 Assignment

    10/32

    for#() for#() for#()

    F

    KE"WC & S

    JU) What is a ZombieO List - e ents that will #ill a Zombie.

    KE"WC & K Zombie is a process that has exited but its parent has not accepted its exit status so itsprocess !> is still allocated.

    The following are the e ents that will #ill a Zombie& the parent exits, the parent executes wait(), or theparent handles the "!;=RL> signal (such as signal("!;=RL>, "!;A!;E)).

    N9) Write a = statement that will suspend process 1-

  • 8/10/2019 Linux 56 Assignment

    11/32

    dup-(fd 1 , 1)

    close(fd 1 )

    exec p(arg1 9 , arg1)

    perror(arg1 9 )

    F

    // Vipe input of cmd- in another child process

    else if ((pid-0for#())009) @

    close(fd 1 )

    dup-(fd 9 , 9)

    close(fd 9 )

    exec p(arg- 9 , arg-)

    perror(arg- 9 )

    F

    // Wait for both children in the parent

    else @

    close(fd 9 )

    close(fd 1 )

    wait(Gstatus1)

    pid0wait(Gstatus-)

    if (pid00pid-)

    return status-77S // cmd- finished last

    else

    return status177S // cmd- finished first

    F

    F

    // K simpler approach that doesn?t re uire chec#ing the pid is to

    // for# a child for cmd- and a grandchild for cmd1.

  • 8/10/2019 Linux 56 Assignment

    12/32

    N-) "uppose a dis# bloc# is -[ bytes (instead of J[) and a pointer is J bytes. Row many double indirectpointers would an inode need to support file siZes up to J ; O

    KE"WC & S (K bloc# holds N1- pointers. S x N1- x N1- x -[ 0 J ; )

    N

  • 8/10/2019 Linux 56 Assignment

    13/32

    NQ) Write = code to set the permissions of file 5fool5 so that only the owner may read or write it

    KE"WC & chmod(5fool5, 9P99)

    NS) Row many processes exist after the followingO

    if (for#()) for#()

    KE"WC &

  • 8/10/2019 Linux 56 Assignment

    23/32

    Q-)

    "olution&

    #!/bin/sh

    size=$1

    for file in * do

    set `du -b $file`if [ $1 -gt $size ]then

    echo $file $1fi

    done

    Q

  • 8/10/2019 Linux 56 Assignment

    24/32

  • 8/10/2019 Linux 56 Assignment

    25/32

    /D Row much does !/ o erhead matterOD Let?s see how performance changes when we ma#e small !/ calls,D compared with large ones.DD 8sage& ./copy infile outfile bloc#AsiZeDD Klso, there?s one bad coding decision here that might causeD us some trouble unrelated to !/ .... can you spot itOD/

    'include :stdio.h7'include :stdlib.h7'include :assert.h7'include :fcntl.h7'include :errno.h7

    int main(int argc, charDD arg ) @assert(argc 00 J)charD inApath 0 arg 1charD outApath 0 arg -siZeAt bufsiZe 0 atoi(arg < )

    int inAfd 0 open( inApath, A > EL_)int outAfd 0 open(outApath, AW EL_ 4 A= CKT, "A! W]8)

    assert( inAfd 7 9)assert(outAfd 7 9)

    int done 0 9char buf bufsiZewhile ( done) @

    int bytesAread 0 read(inAfd, buf, bufsiZe)if (bytesAread : 9 GG errno 00 CK;K!E)

    /D Yust try again D/else if (bytesAread :0 9)done 0 1

    else @int bytesAwritten 0 9while (bytesAwritten : bytesAread) @

    int writtenAthisAtime 0 write(outAfd, G buf bytesAwritten ,bytesAread + bytesAwritten)

    if (writtenAthisAtime : 9 GG errno 00 CK;K!E)

    else if (writtenAthisAtime :0 9)assert(9)

    elsebytesAwritten M0 writtenAthisAtime

    FF

    F

    close( inAfd)close(outAfd)

    F

  • 8/10/2019 Linux 56 Assignment

    26/32

    "olution&

    #!/bin/sh

    size=$1

    for file in * do

    set `du -b $file`if [ $1 -gt $size ]then

    echo $file $1

  • 8/10/2019 Linux 56 Assignment

    27/32

    fidone

    QJ)

    QN) K

    QP) K

  • 8/10/2019 Linux 56 Assignment

    28/32

  • 8/10/2019 Linux 56 Assignment

    29/32

    Kill() and signal() (Dr R K Singla)

    Let us now write a program that communicates between child and parentprocesses using kill() and signal().

    fork() creates the child process from the parent. The pid can be checked to decidewhether it is the child(==0) or the parent (pid = child process id).

    The parent can then send messages to child using the pid and kill().

    The child picks up these signals with signal() and calls appropriate functions.

    /* An e ample of communicating process using signals is sig!talk.c" */

    /* sig!talk.c ### $ ample of how % processes can talk to each other using kill() &signal() */

    /* 'e will fork() % process and let the parent send a few */

    /* signals to it s child */

    /* gcc sig!talk.c #o sig!talk */

    include stdio.h+

    include signal.h+

    ,oid sighup()- /* routines child will call upon sigtrap */

    ,oid sigint()-

    ,oid sig uit()-

    main()

    int pid-

    /* get child process */

    if ((pid = fork()) 0)

    perror( fork )-

    e it(1)-

    2

    if (pid == 0)

    /* child */

    signal(3456789sighup)- /* set function calls */

    signal(3454:T9sigint)-

    signal(345;74T9 sig uit)-

    for(--)- /* loop for e,er */

  • 8/10/2019 Linux 56 Assignment

    30/32

    2

    else /* parent */

    /* pid hold id of child */

    printf(

  • 8/10/2019 Linux 56 Assignment

    31/32

    QQ)

  • 8/10/2019 Linux 56 Assignment

    32/32

    $ipes' pipe is an interprocess communication (")C* mechanism %or two +nix processrunnin on the same machine. ' pipe is a one,wa- communication channel &etweenthe two processes (one process alwa-s writes to one end o% the pipe the otherprocess alwa-s reads %rom the other end o% the pipe*. ' pipe is li e a temporar- lewith two open ends writes to one end &- one process can &e read %rom the other

    end &- the another process. owe#er unli e a re ular le a read %rom a piperesults in the remo#al o% data that was written &- the other process. $he pipe s-stem call is used to create a new pipe. "t creates two le descriptors one %or theread end o% the pipe the other %or the write end o% the pipe. ne o% thecommunicatin processes use the write end o% the pipe to send a messa e to theother communication process who reads %rom the read end:

    When your shell program executes a command with a single pipe li#e the following&

    cat foo.txt F grep Ai ahcat s output will &e pipe ed to grep s input. $he shell process will %or two process(one that will exec cat the other that will exec grep * and will wait %or &oth to nish&e%ore printin the next shell prompt. +se pipe and "/ redirection to set upcommunication &etween the two child processes.

    The pipe reading process #nows when to exit when it reads C B on its input any process bloc#ed on a readwill unbloc# when the file is closed. Rowe er, if multiple processes ha e the same file open, only the lastclose to the file will trigger an C B. Therefore, when you write programs that create pipes (or open files), you

    need to be ery careful about how many processes ha e the files open, so that C B conditions will betriggered.

    QS)