operating system program

Upload: anandhcooolguy

Post on 05-Apr-2018

228 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 Operating System Program..

    1/36

    solution with lockfile:

    #!/bin/bash

    if [ -e number.txt ]; thenecho "File exists"

    elseecho "File does not exists. Create file

    now."echo 1 > number.txt

    fi

    lockfile script.lock

    a=$(/usr/bin/tail -n 1 number.txt)

    if [ $a -gt 1 ]; thena=$(/usr/bin/tail -n 1 number.txt)

    /usr/bin/expr $a - 1 >> number.txtfi

    if [ $a -lt 2 ]; thena=$(/usr/bin/tail -n 1 number.txt)/usr/bin/expr $a + 1 >> number.txt

    fi

    rm -f script.lock

  • 8/2/2019 Operating System Program..

    2/36

    The program in Listing 8.2 opens a file for writing whose name isprovided on the command line, and then places a write lock on it.The program waits for the user to hit Enter and then unlocks andcloses the file.

    Listing 8.2 (lock-file.c) Create a Write Lock withfcntl

    #include

    #include

    #include

    #include

    int main (int argc, char* argv[])

    http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)http://josc_emoticon%28%22/?:%22)
  • 8/2/2019 Operating System Program..

    3/36

    {

    char* file = argv[1];

    int fd;

    struct flock lock;

    printf ("opening %s\n", file);

    /* Open a file descriptor to the file. */

    fd = open (file, O_WRONLY);

    printf ("locking\n");

    /* Initialize the flock structure. */

    memset (&lock, 0, sizeof(lock));

    lock.l_type = F_WRLCK;

    /* Place a write lock on the file. */

    fcntl (fd, F_SETLKW, &lock);

    printf ("locked; hit Enter to unlock... ");

    /* Wait for the user to hit Enter. */

    getchar ();

    printf ("unlocking\n");

    /* Release the lock. */

    lock.l_type = F_UNLCK;

    fcntl (fd, F_SETLKW, &lock);

    close (fd);

  • 8/2/2019 Operating System Program..

    4/36

    return 0;

    }

    Compile and run the program on a test filesay, /tmp/test-

    file

    like this:

    % cc -o lock-file lock-file.c

    % touch /tmp/test-file

    % ./lock-file /tmp/test-file

    opening /tmp/test-file

    locking

    locked; hit Enter to unlock...

    Now, in another window, try running it again on the same file.

    % ./lock-file /tmp/test-file

    opening /tmp/test-file

    locking

    Note that the second instance is blocked while attempting to lock

    the file. Go back to the first window and press Enter:

    unlocking

    The program running in the second window immediately acquiresthe lock.

    If you prefer fcntl not to block if the call cannot get the lock you

    requested, use F_SETLK instead of F_SETLKW. If the lock cannot

    be acquired, fcntl returns

    1 immediately.

    Linux provides another implementation of file locking withthe flock call. The fcntl version has a major advantage: Itworks with files on NFS3file systems (as long as the NFS serveris reasonably recent and correctly configured). So, if you have

    http://popup%28%27/content/images/chap8_0735710430/elementLinks/ch8fn03.html')http://popup%28%27/content/images/chap8_0735710430/elementLinks/ch8fn03.html')http://popup%28%27/content/images/chap8_0735710430/elementLinks/ch8fn03.html')
  • 8/2/2019 Operating System Program..

    5/36

    access to two machines that both mount the same file system viaNFS, you can repeat the previous example using two differentmachines. Run lock-file on one machine, specifying a file onan NFS file system, and then run it again on another machine,

    specifying the same file. NFS wakes up the second programwhen the lock is released by the first program.

    //Shared Memory Segment

    Program 1:

    #include #include #include

    #include #include #define SHMSZ 27

    main(){

    char c;int semid,retval;struct sembuf sop,sop1;int shmid;key_t key;

    char *shm, *s;

  • 8/2/2019 Operating System Program..

    6/36

    key = 5678;semid=semget(20,1,0666|IPC_CREAT);semctl(semid,0,SETVAL,1);if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) avail[j])

    waitcheck=1;

    }if (violationcheck==1)printf(\n\n\t The Process Exceeds its Max Need:

    Terminated);else if(waitcheck==1)printf(\n\n\t Lack of Resourcess : Process State Wait);

    else

    {for(j=0;j

  • 8/2/2019 Operating System Program..

    12/36

    }ch1=safeseq();if(ch1==0){

    printf(\n\n\t Granting leads to Unsafe state : );

    printf(\n\n\t Request Denied );

    for(j=0;j

  • 8/2/2019 Operating System Program..

    13/36

    printf( %d ,p[i].max[j]);printf(\t);for(j=0;j

  • 8/2/2019 Operating System Program..

    14/36

    for(k=0;k

  • 8/2/2019 Operating System Program..

    15/36

    * This module can be compiled using 'cc

    bankersalgorithm.c' and executed using './a.out'

    //inculsion.

    #include

    //macro definition

    #define cls() printf("\033[H\033[J")

    #define delay() for(h=0;h

  • 8/2/2019 Operating System Program..

    16/36

    //inserting the assumed values.

    available_res[0]=3; available_res[1]=1; available_res[2]=1;

    available_res[3]=2;

    cur_allocated_res[0][0]=1;cur_allocated_res[0][1]=2;cur_allo

    cated_res[0][2]=2;cur_allocated_res[0][3]=1;

    cur_allocated_res[1][0]=1;cur_allocated_res[1][1]=0;cur_allo

    cated_res[1][2]=3;cur_allocated_res[1][3]=3;

    cur_allocated_res[2][0]=1;cur_allocated_res[2][1]=1;cur_allo

    cated_res[2][2]=1;cur_allocated_res[2][3]=1;

    max_req_res[0][0]=3; max_req_res[0][1]=3;

    max_req_res[0][2]=2; max_req_res[0][3]=2;

    max_req_res[1][0]=1; max_req_res[1][1]=2;max_req_res[1][2]=3; max_req_res[1][3]=4;

    max_req_res[2][0]=1; max_req_res[2][1]=1;

    max_req_res[2][2]=1; max_req_res[2][3]=0;

    //assuming the request.

    req_queue[0]=0;req_queue[1]=1;req_queue[2]=2;req_queu

    e[3]=0;req_queue[4]=2;req_queue[5]=1;

    req_type[0]=0;req_type[1]=0;req_type[2]=0;req_type[3]=1;re

    q_type[4]=1;req_type[5]=1;display();

    i=0;j=0;

    while(i

  • 8/2/2019 Operating System Program..

    17/36

    getrequest(req_queue[i]);

    printf("\nChecking safe state.....\n");

    delay();

    if(issafe())

    {

    printf("\nSafe state detected....\nAllocating resources

    .......\n");

    allocate(req_queue[i]);

    }

    else

    {

    printf("\nUnsafe state detected....\nInserting the processinto waiting queue.\n");

    j=j+1;

    wait_queue[j]=req_queue[i];

    }

    }

    else

    {

    printf("for resource deallocation.\n");deallocate(req_queue[i]);

    printf("\nDeallocation done.\n\n%d processes in the wait

    queue\n",j);

    if(j>0)

    {

    while(j>0)

    {

    printf("\nConsidering the waiting queue processP%d\n",wait_queue[j]+1);

    getrequest(wait_queue[j]);

    printf("\nChecking safe state.\n");

    delay();

    if(issafe())

  • 8/2/2019 Operating System Program..

    18/36

    {

    printf("\nSafe state detected\nResources allocated\n");

    allocate(wait_queue[j]);

    j--;

    }

    else

    {

    break;

    }

    }

    }

    }delay();

    i++;

    }

    }

    void getrequest(int i)

    {

    int j;

    for(j=0;j

  • 8/2/2019 Operating System Program..

    19/36

    return 1;

    }

    void allocate(int i)

    {

    int j;

    for(j=0;j

  • 8/2/2019 Operating System Program..

    20/36

    printf("\n\n\t\t\t\tDETAILS.");

    printf("\n\t\t\t\t________");

    printf("\n\n\t\tNO OF PROCESSES:\tP1 P2 P3");

    printf("\n\n\t\tNO OF RESOURCES:\tA B C D");

    printf("\n\n\t\t\tThe status .............");

    printf("\nThe available resources are.\n\t\tA B C D\n\t\t");

    for(i=0;i

  • 8/2/2019 Operating System Program..

    21/36

    fgets(a,2,stdin);

    }

    Program for FIFO page replacement algorithm

    #include#includeint fr[3];void main(){

    void display();int i,j,page[12]={2,3,2,1,5,2,4,5,3,2,5,2};int flag1=0,flag2=0,pf=0,frsize=3,top=0;clrscr();for(i=0;i

  • 8/2/2019 Operating System Program..

    22/36

    {flag1=1;flag2=1;break;}}if(flag1==0){for(i=0;i=frsize)top=0;}display();}printf("Number of page faults : %d ",pf);

    getch();}void display(){int i;printf("\n");

  • 8/2/2019 Operating System Program..

    23/36

    for(i=0;i

  • 8/2/2019 Operating System Program..

    24/36

    6789

    1011121314151617

    1819202122232425

    262728293031323334

    353637383940

    void display();intp[12]={2,3,2,1,5,2,4,5,3,2,5,2},i,j,fs[3];int index,k,l,flag1=0,flag2=0,pf=0,frsize=3;clrscr();for(i=0;i

  • 8/2/2019 Operating System Program..

    25/36

    414243444546474849505152

    5354555657585960

    616263646566676869

    for(i=0;i

  • 8/2/2019 Operating System Program..

    26/36

    2 3 12 5 12 5 12 5 42 5 43 5 43 5 23 5 23 5 2no of page faults : 4

    Sockets Example

    Introduct

    ion

    JAVA

    Menu

    Sockets

    Text

    Files

    CSSCSS

    tutorial

    LINUX

    Comman

    This example introduces you to Java socket programming.

    The server listens for a connection. When a connection is

    established by a client. The client can send data. In the

    current example the client sends the message "Hi my

    server". To terminate the connection, the client sends the

    message "bye". Then the server sends the message "bye"

    too. Finally the connection is ended and the server waits for

    an other connection. The two programs should be runned in

    the same machine. however if you want to run them in two

    different machines, you may simply change the adress

    "localhost" by the IP adress of the machine where you will

    run the server.

    The server

    import java.io.*;import java.net.*;

    http://zerioh.tripod.com/ressources/index.htmlhttp://zerioh.tripod.com/ressources/index.htmlhttp://zerioh.tripod.com/ressources/index.htmlhttp://zerioh.tripod.com/ressources/menu.htmlhttp://zerioh.tripod.com/ressources/menu.htmlhttp://zerioh.tripod.com/ressources/sockets.htmlhttp://zerioh.tripod.com/ressources/sockets.htmlhttp://zerioh.tripod.com/ressources/textfiles.htmlhttp://zerioh.tripod.com/ressources/textfiles.htmlhttp://zerioh.tripod.com/ressources/textfiles.htmlhttp://zerioh.tripod.com/ressources/css.htmlhttp://zerioh.tripod.com/ressources/css.htmlhttp://zerioh.tripod.com/ressources/css.htmlhttp://zerioh.tripod.com/ressources/lincommands.htmlhttp://zerioh.tripod.com/ressources/index.htmlhttp://zerioh.tripod.com/ressources/lincommands.htmlhttp://zerioh.tripod.com/ressources/css.htmlhttp://zerioh.tripod.com/ressources/css.htmlhttp://zerioh.tripod.com/ressources/textfiles.htmlhttp://zerioh.tripod.com/ressources/textfiles.htmlhttp://zerioh.tripod.com/ressources/sockets.htmlhttp://zerioh.tripod.com/ressources/menu.htmlhttp://zerioh.tripod.com/ressources/index.htmlhttp://zerioh.tripod.com/ressources/index.html
  • 8/2/2019 Operating System Program..

    27/36

    ds public class Provider{ServerSocket providerSocket;Socket connection = null;ObjectOutputStream out;

    ObjectInputStream in;String message;Provider(){}void run(){

    try{//1. creating a server

    socket

    providerSocket = newServerSocket(2004, 10);//2. Wait for connection

    System.out.println("Waiting forconnection");

    connection =providerSocket.accept();

    System.out.println("Connectionreceived from " +connection.getInetAddress().getHostName());

    //3. get Input and Outputstreams

    out = newObjectOutputStream(connection.getOutputS

    tream());out.flush();in = new

    ObjectInputStream(connection.getInputStream());

    sendMessage("Connection

    http://zerioh.tripod.com/ressources/lincommands.htmlhttp://zerioh.tripod.com/ressources/lincommands.htmlhttp://zerioh.tripod.com/ressources/lincommands.html
  • 8/2/2019 Operating System Program..

    28/36

    successful");//4. The two parts

    communicate via the input and outputstreams

    do{try{

    message =(String)in.readObject();

    System.out.println("client>" +message);

    if

    (message.equals("bye"))

    sendMessage("bye");}

    catch(ClassNotFoundExceptionclassnot){

    System.err.println("Data received

    in unknown format");}

    }while(!message.equals("bye"));}catch(IOException

    ioException){

    ioException.printStackTrace();}finally{

    //4: Closing connectiontry{

    in.close();

  • 8/2/2019 Operating System Program..

    29/36

    out.close();

    providerSocket.close();}

    catch(IOExceptionioException){

    ioException.printStackTrace();}

    }}void sendMessage(String msg)

    { try{out.writeObject(msg);out.flush();

    System.out.println("server>" +msg);

    }catch(IOException

    ioException){

    ioException.printStackTrace();}

    }public static void main(String

    args[]){

    Provider server = newProvider();

    while(true){server.run();

    }}

  • 8/2/2019 Operating System Program..

    30/36

    }

    The client

    import java.io.*;import java.net.*;public class Requester{

    Socket requestSocket;ObjectOutputStream out;ObjectInputStream in;String message;Requester(){}

    void run(){

    try{//1. creating a socket to

    connect to the serverrequestSocket = new

    Socket("localhost", 2004);

    System.out.println("Connected tolocalhost in port 2004");//2. get Input and Output

    streamsout = new

    ObjectOutputStream(requestSocket.getOutputStream());

    out.flush();in = new

    ObjectInputStream(requestSocket.getInputStream());

    //3: Communicating withthe server

    do{try{

  • 8/2/2019 Operating System Program..

    31/36

    message =(String)in.readObject();

    System.out.println("server>" +

    message);sendMessage("Hi

    my server");message = "bye";

    sendMessage(message);}

    catch(ClassNotFoundExceptionclassNot){

    System.err.println("data receivedin unknown format");

    }

    }while(!message.equals("bye"));}

    catch(UnknownHostExceptionunknownHost){

    System.err.println("Youare trying to connect to an unknownhost!");

    }catch(IOException

    ioException){

    ioException.printStackTrace();}finally{

    //4: Closing connectiontry{

  • 8/2/2019 Operating System Program..

    32/36

    in.close();out.close();

    requestSocket.close();

    }catch(IOException

    ioException){

    ioException.printStackTrace();}

    }}

    void sendMessage(String msg){try{

    out.writeObject(msg);out.flush();

    System.out.println("client>" +msg);

    }

    catch(IOExceptionioException){

    ioException.printStackTrace();}

    }public static void main(String

    args[])

    {Requester client = new

    Requester();client.run();

    }}

  • 8/2/2019 Operating System Program..

    33/36

    Servlets - Session Management ExampleAfter user authentication, start a session. Display "Welcome[username]" as the response along with a link that hits anotherServlet. From this other servlet, send the response "You are[username]" by retrieving the username information from thesession as an attribute.

    1) Servlet 1: Code here -http://www.javaissues.com/2011/02/servlets-handling-get-request.html

    2) Servlet 2 - PostServlet.java

    package info.icontraining.servlets;

    import java.io.IOException;import java.io.PrintWriter;

    import javax.servlet.http.*;

    public class PostServlet extends HttpServlet {

    http://www.javaissues.com/2011/02/servlets-handling-get-request.htmlhttp://www.javaissues.com/2011/02/servlets-handling-get-request.htmlhttp://www.javaissues.com/2011/02/servlets-handling-get-request.htmlhttp://www.javaissues.com/2011/02/servlets-handling-get-request.htmlhttp://www.javaissues.com/2011/02/servlets-handling-get-request.htmlhttp://www.javaissues.com/2011/02/servlets-handling-get-request.html
  • 8/2/2019 Operating System Program..

    34/36

    public void doPost(HttpServletRequest

    request, HttpServletResponse response) throwsIOException {

    PrintWriter out = response.getWriter();

    String username =request.getParameter("user");

    String passwd =request.getParameter("pass");

    out.println("");out.println("Post Servlet

    Example");out.println("");

    if (username.equals("dinesh") &&passwd.equals("dinesh")) {

    out.println("Welcome " + username+"!");

    HttpSession session =

    request.getSession();

    session.setAttribute("username",username);out.println("Click here");

    } else {out.println("Invalid username/passwd.

    Go back and try again.");}

    out.println("");out.close();

    }

  • 8/2/2019 Operating System Program..

    35/36

    }

    3) Servlet 3 - LinkedServlet.java

    package info.icontraining.servlets;

    import java.io.IOException;import java.io.PrintWriter;

    import javax.servlet.http.*;

    public class LinkedServlet extends HttpServlet {

    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{

    PrintWriter out = response.getWriter();

    out.println("");out.println("Session

    Management Example");out.println("");

    HttpSession session =request.getSession();

    String username =(String)session.getAttribute("username");

    out.println("You are " + username +"!");

    out.println("");out.close();

    }}

  • 8/2/2019 Operating System Program..

    36/36

    web.xml configuration for Servlets 2 & 3 (for configuration ofServlet 1, go to link specified above)

    postServletinfo.icontraining.servlets.PostServlet

    postServlet/formurl

    linkedServletinfo.icontraining.servlets.LinkedServlet

    linkedServlet/linkedServlet