Showing posts with label assignment. Show all posts
Showing posts with label assignment. Show all posts

Customize Terminal for Linux (Written in C language )

Customize  Terminal for Linux (Written in C language )
#include <stdlib.h>

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

void parseCmd(char* cmd, char** params);
int executeCmd(char** params);

#define MAX_COMMAND_LENGTH 100
#define MAX_NUMBER_OF_PARAMS 10

int main()
{
    char cmd[MAX_COMMAND_LENGTH + 1];
    char* params[MAX_NUMBER_OF_PARAMS + 1];

    int cmdCount = 0;

    while(1) {
        // Print command prompt
        char* username = getenv("USER");
        printf("%s@shell %d> ", username, ++cmdCount);

        // Read command from standard input, exit on Ctrl+D
        if(fgets(cmd, sizeof(cmd), stdin) == NULL) break;

        // Remove trailing newline character, if any
        if(cmd[strlen(cmd)-1] == '\n') {
            cmd[strlen(cmd)-1] = '\0';
        }

        // Split cmd into array of parameters
        parseCmd(cmd, params);

        // Exit?
        if(strcmp(params[0], "exit") == 0) break;

        // Execute command
        if(executeCmd(params) == 0) break;
    }

    return 0;
}

// Split cmd into array of parameters
void parseCmd(char* cmd, char** params)
{   int i=0;
    for(i = 0; i < MAX_NUMBER_OF_PARAMS; i++) {
        params[i] = strsep(&cmd, " ");
        if(params[i] == NULL) break;
    }
}

int executeCmd(char** params)
{
    // Fork process
    pid_t pid = fork();

    // Error
    if (pid == -1) {
        char* error = strerror(errno);
        printf("fork: %s\n", error);
        return 1;
    }

    // Child process
    else if (pid == 0) {
        // Execute command
        execvp(params[0], params);  

        // Error occurred
        char* error = strerror(errno);
        printf("shell: %s: %s\n", params[0], error);
        return 0;
    }

    // Parent process
    else {
        // Wait for child process to finish
        int childStatus;
        waitpid(pid, &childStatus, 0);
        return 1;
    }
}

A solution to the Readers/Writers Problem using semaphores

A solution to the Readers/Writers Problem using semaphores

Introduction

The readers/writers problem is one of the classic synchronization problems. Like the dining philosophers, it is often used to compare and contrast synchronization mechanisms. It is also an eminently practical problem.

Readers/Writers Problem - Classic definition

Two kinds of processes -- readers and writers -- share a database. Readers execute transactions that examine database records; writer transactions both examine and update the database. The database is assumed initially to be in a consistent state (i.e., one in which relations between data are meaningful). Each transaction, if executed in isolation, transforms the database from one consistent state to another. To preclude interference between transactions, a writer process must have exclusive access to the database. Assuming no writer is accessing the database, any number of readers may concurrently execute transactions.
Some time ago at work, we had to implement a server that relays and translates his incoming datafeed to multiple (typically > 32) clients. As this datafeed represents the continuously (but on a non-regular time base) changing (stock/option) market prices, fast relaying is crucial. We developed a solution that consists of one receiving thread, multiple translator threads, and even more sending threads (since we do not want to block the server if a client fails to receive).
Obviously, all the threads need access to the received and / or translated packet. To achieve this without corrupting data, synchronization is necessary. Searching the MSDN, resulted in finding several synchronization objects (CCriticalSectionCMutex, etc.) of which none seem to fulfill our demands: Multiple read-access when not writing. We thus decided to write the desired synchronization object ourselves: CMutexRW.

Formal readers and writers solution using semaphores

Since our problem has extensively been studied (since 1960?) we first turned to some old college-books on parallel formal semantics to refresh our knowledge about the problem. Soon we found the pages describing the readers and writers problem and (several) solution outlines. We chose to implement our solution (with readers preference) using semaphores.
First some quick (probably skipable) refresh course to (formal) semaphores: Semaphores where first introduced by Dijkstra in 1968, who thought it to be an useful tool for implementing mutual exclusion and for signalling the occurrence of events such as interrupts. A semaphore is an instance of an abstract data type: it has a representation that is manipulated only by two special operations, P and V. Because Dijkstra is Dutch, the P andV stand for Dutch words. In particular, P is the first letter of the Dutch word passeren, which means `to pass'; V is the first letter of vrijgeven, which means `to release'. The V operation signals the occurrence of an event; the Poperation is used to delay a process until an event has occurred. In particular, the two operations must be implemented so that they preserve the following property for every semaphore in a program.

N/B: the description is copy and paste......



Dining philosophers problem with GUI in JAVA

Dining philosophers problem with GUI in JAVA

Problem statement


Illustration of the dining philosophers problem.
Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers.
Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when he has both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After he finishes eating, he needs to put down both forks so they become available to others. A philosopher can take the fork on his right or the one on his left as they become available, but cannot start eating before getting both of them.
Eating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed.
The problem is how to design a discipline of behavior (a concurrent algorithm) such that no philosopher will starve; i.e., each can forever continue to alternate between eating and thinking, assuming that no philosopher can know when others may want to eat or think.

Problems

The problem was designed to illustrate the challenges of avoiding deadlock, a system state in which no progress is possible. To see that a proper solution to this problem is not obvious, consider a proposal in which each philosopher is instructed to behave as follows:
  • think until the left fork is available; when it is, pick it up;
  • think until the right fork is available; when it is, pick it up;
  • when both forks are held, eat for a fixed amount of time;
  • then, put the right fork down;
  • then, put the left fork down;
  • repeat from the beginning.
This attempted solution fails because it allows the system to reach a deadlock state, in which no progress is possible. This is a state in which each philosopher has picked up the fork to the left, and is waiting for the fork to the right to become available. With the given instructions, this state can be reached, and when it is reached, the philosophers will eternally wait for each other to release a fork.[4]
Resource starvation might also occur independently of deadlock if a particular philosopher is unable to acquire both forks because of a timing problem. For example there might be a rule that the philosophers put down a fork after waiting ten minutes for the other fork to become available and wait a further ten minutes before making their next attempt. This scheme eliminates the possibility of deadlock (the system can always advance to a different state) but still suffers from the problem of livelock. If all five philosophers appear in the dining room at exactly the same time and each picks up the left fork at the same time the philosophers will wait ten minutes until they all put their forks down and then wait a further ten minutes before they all pick them up again.
Mutual exclusion is the basic idea of the problem; the dining philosophers create a generic and abstract scenario useful for explaining issues of this type. The failures these philosophers may experience are analogous to the difficulties that arise in real computer programming when multiple programs need exclusive access to shared resources. These issues are studied in the branch of concurrent programming. The original problems of Dijkstra were related to external devices like tape drives. However, the difficulties exemplified by the dining philosophers problem arise far more often when multiple processes access sets of data that are being updated. Systems such as operating system kernels use thousands of locks and synchronizations that require strict adherence to methods and protocols if such problems as deadlock, starvation, or data corruption are to be avoided.

Solutions

Resource hierarchy solution

This solution to the problem is the one originally proposed by Dijkstra. It assigns a partial order to the resources (the forks, in this case), and establishing the convention that all resources will be requested in order, and that no two resources unrelated by order will ever be used by a single unit of work at the same time. Here, the resources (forks) will be numbered 1 through 5 and each unit of work (philosopher) will always pick up the lower-numbered fork first, and then the higher-numbered fork, from among the two forks he plans to use. The order in which each philosopher puts down the forks does not matter. In this case, if four of the five philosophers simultaneously pick up their lower-numbered fork, only the highest numbered fork will remain on the table, so the fifth philosopher will not be able to pick up any fork. Moreover, only one philosopher will have access to that highest-numbered fork, so he will be able to eat using two forks.
While the resource hierarchy solution avoids deadlocks, it is not always practical, especially when the list of required resources is not completely known in advance. For example, if a unit of work holds resources 3 and 5 and then determines it needs resource 2, it must release 5, then 3 before acquiring 2, and then it must re-acquire 3 and 5 in that order. Computer programs that access large numbers of database records would not run efficiently if they were required to release all higher-numbered records before accessing a new record, making the method impractical for that purpose.



Contact list using Linkedlist in c++

Contact list using Linkedlist in c++
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
struct node
{
    char  number[50];
    char  name[50];

    struct node* next;
};
struct node* head=NULL;
FILE *fp,*wfp;
bool searching(char value[])
{
    node *current;
    current=head;
    while(current!=NULL)
    {
        if(strcmp(current->number,value)==0)
        {
            puts(current->name);
            puts(current->number);
            return true;
        }
        current=current->next;
    }
    return false;
}
void insert(char *name,char  *number)
{
    struct node* element;
    element = new struct node;
    strcpy(element->name,name);
    strcpy(element->number,number);
    element->next = NULL;

    if(head==NULL)
    {
        head = element;
    }
    else
    {
        struct node* current;
        for(current=head;current->next!=NULL;current=current->next);

        current->next = element;
    }
}
void print()
{
    struct node* current;
    for(current=head;current!=NULL;current=current->next)
    {
        puts(current->name);
        puts(current->number);
        puts("\n");
    }
    printf("\n");
}
void remove(char *value)
{
    struct node *current,*prev;
    prev=NULL;
    for(current=head;current->next!=NULL;current=current->next)
    {
        if(strcmp(current->number,value)==0)
            break;
        prev = current;

    }
    if(prev==NULL)
    {
        head = current->next;
    }
    else
    {
            prev->next = current->next;
    }
    free(current);
}

bool modify(char *name,char *number,char value[])
{
    node *current;
    current=head;
    while(current!=NULL)
    {
        if(strcmp(current->number,value)==0)
        {
            strcpy(current->name,name);
            strcpy(current->number,number);
            return true;
        }
        current=current->next;
    }
    return false;
}
int main()
{
    fp=fopen("phonebook.txt","r");

    while(1){
    printf("<===============Phone-Book Menu============>\n");
    printf("Enter 1 for Add a phone number\n");
    printf("Enter 2 for Delete a phone number\n");
    printf("Enter 3 for Modify a phone number\n");
    printf("Enter 4 for Search a phone number\n");
    printf("Enter 5 for print a deatils\n");
    printf("Enter 0 for Exit a phone number\n");

    int cas;
    scanf("%d",&cas);
    getchar();
    char name[50],number[50],temp[50];



        switch(cas)
        {
        case 1:
            printf("Please enter your contact name :");


            scanf("%s",name);
            printf("\nPlease enter your contact number :");
            scanf("%s",number);
            insert(name,number);
            printf("\nSucsessfully insterted\n");
            break;

        case 2:
            printf("\nEnter number for delete: ");

            scanf("%s",temp);
            remove(temp);
            printf("\nSucsessfully deleted\n");

            break;
        case 3:
             printf("\nEnter number for modify: ");

            scanf("%s",temp);
            printf("Please enter your contact name :");


            scanf("%s",name);
            printf("\nPlease enter your contact number :");
            scanf("%s",number);

            if(modify(name,number,temp))
                printf("\nSucsessfully modify\n");
            printf("\nUnsucsessfully modify\n");


            break;
        case 4:
            printf("\nEnter number for remove: ");
            scanf("%s",temp);
            if(!searching(temp))
                printf("contact not found");
            break;
        case 5:
            print();
            break;
        case 0:
            exit(0);
            break;

        }

    }
    return 0;
}

Get Time in shell script

Get Time in shell script


#!/bin/bash
NOW=$(date +"%r")

echo "===============Time is $NOW===================="

hour=${NOW:0:2}
min=${NOW:3:2}
sec=${NOW:6:2}
t=${NOW:9:2}

wh="$(whoami)"



if [[ ( "$t" = "AM" && "$hour" = "12" ) || ( "$t" = "AM" && "$hour" -ge 1 && "$hour" -le 11 ) ]]
then echo "Good Morning  $wh"
elif [[ ( "$t" = "PM" && "$hour" = "12" ) || ( "$t" = "PM" && "$hour" -ge 1 && "$hour" -le 5 ) ]]
then echo "Good Afternoon  $wh"
elif [[ ( "$t" = "PM" && "$hour" -ge 6 && "$hour" -le 11 ) ]]
then echo "Good Evening  $wh"
fi

Assembly code

Assembly code

For each of the following problem you should take a number (Range: 1 -
9)as size of the pattern. Your task is to print the patterns.
1)Right Angled Triangle with ‘*’: For input 9 following will be printed
2) Reversed Right Angled Triangle with ‘*’: For input 9 following will be printed
3) Pyramid with ‘*’: For input 9 following will be printed
4) Reversed Right Angled Triangle with Numbers: For input 9 following will be
printed
For input 6 following will be printed
5) Reversed Right Angled Triangle with Numbers: For input 9 following will be
printed
6) Pyramid with Numbers: For input 9 following will be printed
For input 6 following will be printed
=============================Solution===============================

Assignment-1
********************************************


.MODEL SMALL
.STACK 100H
.DATA 


CR EQU 0DH  ;CARRIGE RETURN       NEW LINE
LF EQU 0AH  ;LINEFREED  


MSG1 DB  'I AM AMIT$'
  
NEWLINE DB  CR,LF ,'$' 

I DB ?  
J DB ?
N DB ?

.CODE
MAIN PROC
    MOV AX,@DATA
    MOV DS ,AX
    
    MOV AH,01H ;INPUT
    INT 21H 
    
    MOV N,AL
     
     
    MOV AH,9      ;INPUT AFTER NEWLINE
    LEA DX,NEWLINE
    INT 21H
    
    
    
    MOV I,'1'
    
LOOP1:
    MOV AL,N
    CMP I,AL
    MOV J,'1'
    JLE LOOP2
    
INCRE1:  
    MOV AL,01H  ;INCREAMENT
    ADD I,AL
    
    
    
    MOV AL,N
    CMP I,AL
    
    MOV AH,9         ;PRINT NEWLINE
    LEA DX,NEWLINE
    INT 21H
    
    
    JG EXIT
    JMP LOOP1
    
    
    
    
    
LOOP2:
    
    MOV AL,I
    CMP J,AL
    JLE PRINTSTAR 
    
    
    
INCRE2:
    MOV AL,1
    ADD J,AL 

    MOV AL,I
    CMP J,AL
    JG INCRE1
    JMP LOOP2 
    

     
 PRINTSTAR:
    MOV AH,2
    MOV DL,'*'
    INT 21H 
    JMP INCRE2   
    
EXIT:    
    MOV AH,4CH
    INT 21H
    
    MAIN ENDP
END MAIN

************************************

Assignment-2

***********************************


.MODEL SMALL
.STACK 100H
.DATA 


CR EQU 0DH  ;CARRIGE RETURN       NEW LINE
LF EQU 0AH  ;LINEFREED  


MSG1 DB  'I AM AMIT$'
  
NEWLINE DB  CR,LF ,'$' 

I DB ?  
J DB ?
N DB ?

.CODE
MAIN PROC
    MOV AX,@DATA
    MOV DS ,AX
    
    MOV AH,01H ;INPUT
    INT 21H 
    
    MOV N,AL
     
     
    MOV AH,9      ;INPUT AFTER NEWLINE
    LEA DX,NEWLINE
    INT 21H
    
    
    
    MOV I,'1'
    
LOOP1:
    MOV AL,I
    MOV J,AL
    MOV AL,N
    CMP I,AL
    
    JLE LOOP2
    
    
    
INCRE1:  
    MOV AL,01H  ;INCREAMENT
    ADD I,AL
    
    
    
    MOV AL,N
    CMP I,AL
    
    MOV AH,9         ;PRINT NEWLINE
    LEA DX,NEWLINE
    INT 21H
    
    
    JG EXIT
    JMP LOOP1
    
    
    
    
    
LOOP2:
    
    MOV AL,N
    CMP J,AL
    JLE PRINTSTAR 
    
    
    
INCRE2:
    MOV AL,1
    ADD J,AL 

    MOV AL,N
    CMP J,AL
    JG INCRE1
    JMP LOOP2 
    

     
     
 PRINTSTAR:
    MOV AH,2
    MOV DL,'*'
    INT 21H 
    JMP INCRE2   
    
EXIT:    
    MOV AH,4CH
    INT 21H
    
    MAIN ENDP
END MAIN



******************************************************
Assignment-3
******************************************************

              .MODEL SMALL
.STACK 100H
.DATA 


CR EQU 0DH  ;CARRIGE RETURN       NEW LINE
LF EQU 0AH  ;LINEFREED  


MSG1 DB  'I AM AMIT$'
  
NEWLINE DB  CR,LF ,'$' 

I DB ?  
J DB ? 
K DB ?
L DB ?
N DB ?

.CODE
MAIN PROC
    MOV AX,@DATA
    MOV DS ,AX
    
    MOV AH,01H ;INPUT
    INT 21H 
    
    MOV N,AL
     
     
    MOV AH,9      ;INPUT AFTER NEWLINE
    LEA DX,NEWLINE
    INT 21H
    
    
    
    MOV I,'1'
    
LOOP1:
    MOV AL,I   ;J=I
    MOV J,AL 
    
    MOV AL,'1'   ;K=1
    MOV K,AL 
    
    MOV L,AL  ;L=1
    
    MOV AL,N
    CMP I,AL
    
    JLE LOOP2
    
    
    
INCRE1:  
    MOV AL,01H  ;INCREAMENT
    ADD I,AL
    
    
    
    MOV AL,N
    CMP I,AL
    
    MOV AH,9         ;PRINT NEWLINE
    LEA DX,NEWLINE
    INT 21H
    
    
    JG EXIT
    JMP LOOP1
    
    
    
    
    
LOOP2:
    
    MOV AL,N
    CMP J,AL
    JL PRINTSPACE 
    
    
    
INCRE2:
    MOV AL,1
    ADD J,AL 

    MOV AL,N
    CMP J,AL
    JGE LOOP3 ;;;;
    JMP LOOP2 
    
     
    
LOOP3:
    MOV AL,I 
    CMP K,AL
    JLE PRINTSTAR
    
    
    
INCRE3:
    MOV AL,01H
    ADD K,AL
    
    MOV AL,I
    CMP K,AL
    
    
    
    JG LOOP4  
    JMP LOOP3
    
        
    
LOOP4:
    MOV AL,I 
    CMP L,AL
    JL PRINTSTAR4
    
    
    
INCRE4:
    MOV AL,01H
    ADD L,AL
    
    MOV AL,I
    CMP L,AL
    JGE INCRE1  
    JMP LOOP4
    
        
    
      
    

    
    
    
    

       
PRINTSPACE:
    MOV AH,2
    MOV DL,' '
    INT 21H 
    JMP INCRE2       
     
 PRINTSTAR:
    MOV AH,2
    MOV DL,'*'
    INT 21H 
    JMP INCRE3 
    
 PRINTSTAR4:
    MOV AH,2
    MOV DL,'*'
    INT 21H 
    JMP INCRE4   
    
EXIT:    
    MOV AH,4CH
    INT 21H
    
    MAIN ENDP
END MAIN

*****************************************************
Assignment-4
*****************************************************

.MODEL SMALL
.STACK 100H
.DATA 


CR EQU 0DH  ;CARRIGE RETURN       NEW LINE
LF EQU 0AH  ;LINEFREED  



  
NEWLINE DB  CR,LF ,'$' 

I DB ?  
J DB ?
N DB ? 
P DB ?

.CODE
MAIN PROC
    MOV AX,@DATA
    MOV DS ,AX
    
    MOV AH,01H ;INPUT
    INT 21H 
    
    MOV N,AL
     
     
    MOV AH,9      ;INPUT AFTER NEWLINE
    LEA DX,NEWLINE
    INT 21H
    
    
    
    MOV I,'1'
    
    
    
LOOP1: 
    MOV AL,N    ;P=N
    MOV P,AL

    MOV AL,I
    MOV J,AL      ;J=I
    MOV AL,N
    CMP I,AL
    
    JLE LOOP2
    
    
    
INCRE1:  
    MOV AL,01H  ;INCREAMENT
    ADD I,AL
    
    
    
    MOV AL,N
    CMP I,AL
    
    MOV AH,9         ;PRINT NEWLINE
    LEA DX,NEWLINE
    INT 21H
    
    
    JG EXIT
    JMP LOOP1
    
    
    
    
    
LOOP2:
    
    MOV AL,N
    CMP J,AL
    JLE PRINTSTAR 
    
    
    
INCRE2:
    MOV AL,1
    ADD J,AL 

    MOV AL,N
    CMP J,AL
    JG INCRE1
    JMP LOOP2 
    
     
    
    
    
    
    

    
    
    
    

       
     
     
 PRINTSTAR:
    MOV AH,2
    MOV DL,P
    INT 21H 
    MOV AL,01H
    SUB P,AL
    JMP INCRE2   
    
EXIT:    
    MOV AH,4CH
    INT 21H
    
    MAIN ENDP
END MAIN


*******************************************************
Assignment-5
******************************************************
            .MODEL SMALL
.STACK 100H
.DATA 


CR EQU 0DH  ;CARRIGE RETURN       NEW LINE
LF EQU 0AH  ;LINEFREED  


MSG1 DB  'I AM AMIT$'
  
NEWLINE DB  CR,LF ,'$' 

I DB ?  
J DB ? 
K DB ?
L DB ?
N DB ?

.CODE
MAIN PROC
    MOV AX,@DATA
    MOV DS ,AX
    
    MOV AH,01H ;INPUT
    INT 21H 
    
    MOV N,AL
     
     
    MOV AH,9      ;INPUT AFTER NEWLINE
    LEA DX,NEWLINE
    INT 21H
    
    
    
    MOV I,'1'
    
LOOP1:           ;for(int i=1;i<=n;i++)
    MOV AL,I   ;J=I      
    MOV J,AL 
    
    MOV AL,'1'   ;K=1
    MOV K,AL 
    
    MOV L,AL  ;L=1
    
    MOV AL,N
    CMP I,AL
    
    JLE LOOP2
    
    
    
INCRE1:  
    MOV AL,01H  ;INCREAMENT
    ADD I,AL
    
    
    
    MOV AL,N
    CMP I,AL
    
    MOV AH,9         ;PRINT NEWLINE
    LEA DX,NEWLINE
    INT 21H
    
    
    JG EXIT
    JMP LOOP1
    
    
    
    
    
LOOP2:  ; for(int J=i;J<n;J++)
    
    MOV AL,N
    CMP J,AL
    JL PRINTSPACE 
    
    
    
INCRE2:
    MOV AL,1
    ADD J,AL 

    MOV AL,N
    CMP J,AL
    JGE LOOP3 ;;;;
    JMP LOOP2 
    
     
    
LOOP3:     ;1 TO K<=I
    MOV AL,I 
    CMP K,AL
    JLE PRINTSTAR
    
    
    
INCRE3:
    MOV AL,01H
    ADD K,AL
    
    MOV AL,I
    CMP K,AL
    
    
    
    JG LOOP4  
    JMP LOOP3
    
        
    
LOOP4:   ;1 TO L<I
    MOV AL,I 
    CMP L,AL
    JL PRINTSTAR4
    
    
    
INCRE4:
    MOV AL,01H
    ADD L,AL
    
    MOV AL,I
    CMP L,AL
    JGE INCRE1  
    JMP LOOP4
    
        
    
      
    

    
    
    
    

       
PRINTSPACE:
    MOV AH,2
    MOV DL,' '
    INT 21H 
    JMP INCRE2       
     
 PRINTSTAR:
    MOV AH,2
    MOV DL,K
    INT 21H 
    JMP INCRE3 
    
 PRINTSTAR4:
    MOV AH,2
    
    MOV AL,I
    MOV BL,L
    
    SUB BL,030H   ; CHAR TO INT
    SUB AL,BL
    
   
    
    MOV DL,AL
    INT 21H 
    JMP INCRE4   
    
EXIT:    
    MOV AH,4CH
    INT 21H
    
    MAIN ENDP
END MAIN