SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
Unix Lab

                           IPC Using Message Queues

#include<stdio.h>
#include<sys/ipc.h>
#include<string.h>
main()
{
      int id;
      struct
      {
              int type;
              char a[20];
      }s;
      key_t k=984171582;
      s.type=1;
      id=msgget(k,IPC_CREAT|0666);
      strcpy(s.a,"Welcome");
      msgsnd(k,s.a,50,0);
      printf("n Msg sent");
      msgrcv(k,&s,50,0,0);
      printf("n Msg is:%sn",s.a);
}

Output :

vinhai@vinhai-desktop$ gcc ms.c
vinhai@vinhai-desktop$ ./a.out

Msg sent
Msg is:Welcome

vinhai@vinhai-desktop$
IPC Using Pipes

#include<stdio.h>
#include<sys/ipc.h>
#include<string.h>
main()
{
      int id,fd[2];
      char s[40];
      id=fork();
      if(id>0)
      {
              printf("n Pareent Process n");
              strcpy(s,"n Hello child n");
              write(fd[1],s,20);
              sleep(3);
              read(fd[0],s,20);
              printf("n %s",s);
      }
      else
      {
              printf("n Child Process n");
              strcpy(s,"n Hello Parent n");
              printf("n Reading Msg:%s",s);
              write(fd[1],s,20);
      }
}

Output :

vinhai@vinhai-desktop$ cc ipcp.c
vinhai@vinhai-desktop$ ./a.out

Child Process
Reading Message : Hello Parent
Parent Process
Hello Child

vinhai@vinhai-desktop$
IMPLEMENTATION OF WAIT & SIGNAL USING COUNTING SEMAPHORE

#include<unistd.h>
#include<stdio.h>
#include<sys/sem.h>
#include<sys/types.h>
void wait(int s)
{
while(semctl(s,0,GETVAL,0)<=0)
semctl(s,0,SETVAL,semctl(s,0,GETVAL,0)-1);
}
void signal(int s)
{
semctl(s,0,SETVAL,semctl(s,0,GETVAL,0)+1);
}
int main()
{
int pid,semid,i;
printf("n Implementetion Using Counting Semaphoren");
semid = semget(0x21,1,0666|IPC_CREAT);
pid = fork();
wait(semid);
printf("nt Process,%d,START[",getpid());
for(i = 0;i<5;i++)
{
printf((pid ==0?"*" : "#"));
fflush(stdout);
sleep(1);
}
printf("]ENDn");
signal(semid);
if(pid>0)
{
wait(0);
semctl(semid,0,IPC_RMID,0);
}
return 0;
}
Output :

vinhai@vinhai-desktop$ cc semc.c
vinhai@vinhai-desktop$ ./a.out

Implementetion Using Counting Semaphore

     Process,1714,START[####]END
     Process,1714,START[****]END

vinhai@vinhai-desktop$
IMPLEMENTATION OF WAIT & SIGNAL USING BINARY SEMAPHORE

#include<stdio.h>
#include<sys/types.h>
#include<sys/sem.h>
main()
{
int semid,pid;
struct sembuf sop;
semid = semget((key_t)35,1,IPC_CREAT|0666);
pid=fork();
if(pid==0)
{
sleep(2);
printf("Child Before Semop n");
sop.sem_num = 0;
sop.sem_op = 0;
sop.sem_flg = 0;
semop(semid,&sop,1);
printf("Child Over n");
} else {
printf("Before 1 Semaphore n");
semctl(semid,0,SETVAL,1);
Printf("PARENT SLEEPn");
sleep(5);
printf("Parent Before 2 Semaphore n");
semctl(semid,0,SETVAL,0);
Printf("PARENT Over n");
}
}
Output :

vinhai@vinhai-desktop$ cc semb.c
vinhai@vinhai-desktop$ ./a.out

 Before 1 Semaphore
PARENT SLEEP
Child Before Semop
Parent Before 2 Semaphore
PARENT Over
Child Over
vinhai@vinhai-desktop$
AUTOMIC COUNTER UPDATE PROBLEM
#include<stdio.h>
#include<unistd.h>
#include<sys/shm.h>
#include<sys/sem.h>
#include<sys/ipc.h>
#include<sys/types.h>
#define key 204
main()
{
 int balance = 500;
 static struct sembuf unlock[1] = {0,-1,IPC_NOWAIT};
 static struct sembuf lock[2] = {0,0,0,0,1,0};
 int semid = semget(key,1,IPC_CREAT|0666);
 int shmid,pid,deposit,withdraw ;
 void *shmptr;
 struct shmid_ds myshmid_ds;
 shmid = shmget(IPC_PRIVATE,1,0666|IPC_CREAT);
 if(semid<1)
 {
  printf(" Semaphore not created ");
 }
 pid = fork();
 if(pid != 0)
 {
  shmptr = shmat(shmid,0,SHM_R);
  sleep(5);
  semop(semid,&lock[0],2);
  balance = *(int *)shmptr;
  printf("n Enter the With Draw Ammount : Rs. ");
  scanf("%d",&withdraw);
  balance = balance-withdraw;
  printf("n Balance After the With Draw Ammount : Rs. %d",balance);
semop(semid,&unlock[0],1);
 }
else
 {
  shmptr = shmat(shmid,0,SHM_W);
  semop(semid,&lock[0],2);
  printf("n Enter the Deposit Ammount : Rs. ");
  scanf("%d",&deposit);
  balance = balance + deposit;
  *(int *)shmptr = balance;
  printf("n Balance After Deposit : Rs. %d n",balance);
  semop(semid,&unlock[0],1);
 }
 shmctl(shmid,IPC_RMID,&myshmid_ds);
 semctl(semid,0,IPC_RMID,0);
}




Output :

vinhai@vinhai-desktop$ cc atomic.c
vinhai@vinhai-desktop$ ./a.out

Enter the Deposit Ammount : Rs. 1000

Balance After Deposit : Rs. 1500
Enter the With Draw Ammount : Rs. 500
Balance After the With Draw Ammount : Rs. 1000

vinhai@vinhai-desktop$
Counting Semaphores At The User Level Using Binary Semaphores

#include<stdio.h>
#include<unistd.h>
#include<sys/sem.h>
#include<sys/ipc.h>
#include<sys/types.h>
#define SEM1 0
#define SEM2 1
#define SEM3 2
int count = 3,semid;
struct sembuf wait1 = {SEM1,-1,SEM_UNDO};
struct sembuf signal1 = {SEM1,1,IPC_NOWAIT};
struct sembuf wait2 = {SEM2,-1,SEM_UNDO};
struct sembuf signal2 = {SEM2,1,IPC_NOWAIT};
struct sembuf wait3 = {SEM3,-1,SEM_UNDO};
struct sembuf signal3 = {SEM3,1,IPC_NOWAIT};
main()
{
int pid;
union semun
{
int val;
}
mysemum;
void countwait();
void countsignal();
semid = semget(IPC_PRIVATE,3,0666|IPC_CREAT);
mysemun.val = 1;
semctl(semid,SEM1,SETVAL,mysemun);
semctl(semid,SEM3,SETVAL,mysemun);
mysemun.val = 0;
semctl(semid,SEM2,SETVAL,mysemun);
pid = fork();
if(pid != 0)
{
countwait();
countwait();
countwait();
countsignal();
countwait();
countsignal();
countsignal();
countsignal();
countwait();
countsignal();
}
}
void countwait()
{
semop(semid,&wait3,1);
semop(semid,&wait1,1);
count = count -1;
printf("n Counting Semaphore After Wait is : %d",count);
if(count<0)
{
printf("n Counting Semaphore less than zero ");
printf("n sSem1 : Signal1");
semop(semid,&signal1,1);
printf("n sSem2 : wait");
}
else
{
semop(semid,&signal1,1);
semop(semid,&signal1,1);
}
}
void countsignal()
{
semop(semid,&wait1,1);
count = count +1;
printf("n Value of Counting Semaphore After Signal is : %d",count);
if(count<=0)
{
semop(semid,&signal2,1);
printf("n Semaphore Count less than zero signaling sem1 &sem3");
}
semop(semid,&signal1,1);
semop(semid,&signal1,1);
}
Output :

vinhai@vinhai-desktop$ cc csem.c
vinhai@vinhai-desktop$ ./a.out

Counting Semaphore After Wait is : 2
Counting Semaphore After Wait is : 1
Counting Semaphore After Wait is : 0
Value of Counting Semaphore After Signal   is : 1
Value of Counting Semaphore After Signal   is : 1
Value of Counting Semaphore After Signal   is : 2
Value of Counting Semaphore After Signal   is : 3
Counting Semaphore After Wait is : 2
Value of Counting Semaphore After Signal   is : 3

vinhai@vinhai-desktop$
SIGNALING PROCESS
#include<stdio.h>
#include<signal.h>
void s()
{
      printf("n This is my signal");
}
main()
{
      printf("n Before signal");
      signal(SIGALRM,s);
      alarm(2);
      pause();
      printf("n After Signal n ");
}




OUTPUT :

vinhai@vinhai-desktop$ cc si.c
vinhai@vinhai-desktop$ ./a.out

Before signal
This is my signal
After Signal

vinhai@vinhai-desktop$
DEADLOCK DETECTION
#include<stdio.h>
#include<stdlib.h>
main()
{
       int i,n,j,al[10],re[10];
       printf("enter the no process : ");
       scanf("%d",&n);
       for(i=1;i<=n;i++)
       {
         printf("enter the resourse allocated and need for process : %d ",i," ");
         scanf("%d%d",&re[i],&al[i]);
       }
        for(i=1;i<=n;i++)
          {
           for(i=j;j<=n;j++)
       {
           if(re[i]==al[j])
     {
            printf("p%d is deadlock because r%d allocated for : p%d",i,re[i],j);
            exit(0);
       }
       }
     }
 }

OUTPUT :

vinhai@vinhai-desktop$ cc deadlock.c
vinhai@vinhai-desktop$ ./a.out

enter the no process : 2
enter the resourse allocated and need for process : 1 1
2
enter the resourse allocated and need for process : 2 2
1
Segmentation fault

vinhai@vinhai-desktop$
PROCESS SCHEDULING (FCFS)
#include<stdio.h>
main()
{
      int i,n,t=0,s=0,b[10],t1;
      printf("n enter the no of values : ");
      scanf("%d",&n);
      printf("n enter the times : ");
      for(i=0;i<n;i++)
      scanf("%d",&b[i]);
      printf("ntprocesstttimettstartttendttwait");
      for(i=0;i<n;i++)
      {
              s=s+b[i];
              printf("nt%dtt%dtt%dtt%dtt%d",i+1,b[i],t,s,t);
              t1=t;
              t=s;
      }
      printf("n avg time%dn",s/n);
      printf("b avg waiting time %d n",t1/n);
}

OUTPUT :

vinhai@vinhai-desktop$ cc fcfs.c
vinhai@vinhai-desktop$ ./a.out

 enter the no of values : 2
 enter the times : 1
3
       process       time        start         end          wait

      1             1            0             1            0

      2             3            1             4            1

avg time 2
avg waiting time 0

vinhai@vinhai-desktop$
PROCESS SCHEDULING (LEAST FREQUENTLY USED)
#include<stdio.h>
main()
{
      int i,j,n,t,a[10],s=0,e=0;
      printf("n Enter the n value : ");
      scanf("%d",&n);
      printf("n Enter the s value : ");
      for(i=0;i<n;i++)
      scanf("%d",&a[i]);
      for(i=0;i<n;i++)
      {
              for(j=i+1;j<n;j++)
              {
                     if(a[i]>a[j])
                     {
                            t=a[i];
                            a[i]=a[j];
                            a[j]=t;
                     } }}
      printf("n Process Time Start End Wait ");
      for(i=0;i<n;i++)
      {
              s=s+a[i];
              printf("n %dt%dt%dt%dt%d n ",i+1,a[i],e,s,e);
              e=s;
      }
}

OUTPUT :
vinhai@vinhai-desktop$ gcc i.c
vinhai@vinhai-desktop$ ./a.out
 Enter the n value3
 Enter the s value2
3
4
   Process Time Start End           Wait
       1        1   0       1        0
       2        2   1       3        1
       3        3   3       6        3
vinhai@vinhai-desktop$
PROCESS SCHEDULING (ROUND ROBIN)
#include<stdio.h>
main()
{
      int i,a[10],n,ts,t=0;
      printf("n Enter the Process & Time-Slice : ");
      scanf("%d %d",&n,&ts);
      printf("n Enter the Time ");
      for(i=0;i<n;i++)
      scanf("%d",&a[i]);
      printf("n Process Time : ");
st:
      t=0;
      for(i=0;i<n;i++)
      {
              if(a[i]>=ts)
              {
                     a[i]=a[i]-ts;
                     printf("n %d %d n",i+1,ts);
                     t++;
              } else if(a[i]!=0) {
                     printf("n %d   %d n ",i+1,a[i]);
                     a[i]=0;
              }}
      if(t>0)
              goto st;
}

OUTPUT :

vinhai@vinhai-desktop$ cc rr.c
vinhai@vinhai-desktop$ ./a.out
 Enter the Process & Time-Slice : 2
2
 Enter the Time 3
1
 Process Time :
 1           2
 2           1
 1           1
 vinhai@vinhai-desktop$
PRODUCER CONSUMER PROBLEM WITH
                  LIMITED BUFFERS
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/shm.h>
#define NELEN 4
#define SEMPTY 0
#define SFULL 1
main()
{
      int pid,semid,shmid,status,i;
      char elem;
      union semun
      {
       int val;
      }mysemnum;
      struct sembuf waitempty={SEMPTY,-1,SEM_UNDO};
      struct sembuf signalempty={SEMPTY,1,IPC_NOWAIT};
      struct sembuf waitfull={SFULL,-1,SEM_UNDO};
      struct sembuf signalfull={SFULL,1,IPC_NOWAIT};
      struct shmid_ds myshmid_ds;
      void *shmptr;
      semid = semget(IPC_CREAT|0666,IPC_PRIVATE<2);
      if(semid<0)
      {
       printf("Semop Creation Error n");
      }
      mysemnum.val=NELEN;
      semctl(semid,SEMPTY,SETVAL,mysemnum);
      mysemnum.val=0;
      semctl(semid,SFULL,SETVAL,mysemnum);
      shmid=shmgat(IPC_PRIVATE,NELEN,0666|IPC_CREAT);
if(shmid<0)
{
 printf("Shared Memory Errorn");
}
pid=fork();
if(pid<0)
{
 printf("Proccess Creation Errorn");
}
if(pid==0)
{
 shmptr=shmat(shmid,0,SHM_R);
 for(i=0;i<4;i++)
 {
 semop(semid,&waitfull,1);
 elem=*((char *)shmptr+(i%NELEN));
 printf("Consumed Element : %c n",elem);
 semop(semid,&signalempty,1);
 sleep(1);
} } else {
 shmptr=shmat(shmid,0,SHM_W);
 for(i=0;i<4;i++)
 {
 semop(semid,&waitempty,1);
 elem='a'+i;
 printf("Consumed Element : %c n",elem);
 *((char *)shmptr+(i%NELEN))=elem;
 semop(semid,&signalfull,1);
 sleep(1);
}
}
wait(& status);
shmctl(shmid,IPC_RMID,&myshmid_ds);
semctl(semid,SEMPTY,IPC_RMID,&mysemnum);
}
OUTPUT :

vinhai@vinhai-desktop$ cc prod.c
vinhai@vinhai-desktop$ ./a.out

Prodced Element : a
Consumed Element : a
Prodced Element : a
Consumed Element : a
Prodced Element : a
Consumed Element : a
Prodced Element : a
Consumed Element : a
Prodced Element : a
Consumed Element : a

vinhai@vinhai-desktop$
DINING PHILOSOPHER PROBLEM
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#define N 3
#define EATING 1
#define THINKING 1
#define left(p) (p)
#define right(p) ((P)+1%N)
typedef int *Semaphore;
Semaphore spoon[N];
void philosopher(int me);
void pick_up(int me);
void pick_down(int me);
void signal(Semaphore s)
int main()
{
       system("clear");
       int i,n;
       for(i=0;i<N;i++)
       {
        spoon[i]=make_sema();
        signal(spoon[i]);
       }
       for(i=0;i<n;i++)
       {
        if(fork()==0)
        break;
        philosopher(i);
       }
       return 0;
}

void philosopher(int me)
{
      char *s;
      int i;
      for(i=1;i<2;i++)
      {
       pick_up(me);
       printf("Philosopher %d eating for th time n",me,i);
sleep(EATING);
       pick_down(me);
       printf("Philosopher %d eating for th time n",me,i);
       sleep(THINKING);
      }
}

void pick_up(int me)
{
      if(me==0)
      {
       wait(spoon[right(me)]);
       printf("Philosopher %d picks up right spoon n",me);
       sleep(1);
       wait(spoon[left(me)]);
       printf("Philosopher %d picks up right spoon n",me);
      }
      else
      {
       wait(spoon[left(me)]);
       printf("Philosopher %d picks up right spoon n",me);
      }
}

void pick_down(int me)
{
      signal(spoon[left(me)]);
      signal(spoon[right(me)]);
}

void signal(Semaphore s)
{
       if(write(s[1],"x",1)<=0)
       {
        printf("Error ! Write() failed, check semaphore creation n");
        exit(1);
       }
}
void wait(Semaphore s)
{
      int junk;
      if(read(s[0],&junk,1)<=0)
      {
       printf("Error ! Write() failed, check semaphore creation n");
       exit(1);
      }
}

Semaphore make_sema(void)
{
     int *sema;
     sema = (int *)calloc(2,siyeof(int));
     pipe(sema);
     return sema;
}

OUTPUT :

vinhai@vinhai-desktop$ cc phil.c
vinhai@vinhai-desktop$ ./a.out

Philosopher 0 picks up right spoon
Philosopher 0 picks up left spoon
Philosopher 0 eating for the 1 time
Philosopher 0 thnking for the 1 time

Philosopher 1 picks up right spoon
Philosopher 1 picks up left spoon
Philosopher 1 eating for the 1 time
Philosopher 1 thnking for the 1 time

Philosopher 2 picks up right spoon
Philosopher 2 picks up left spoon
Philosopher 2 eating for the 1 time
Philosopher 2 thnking for the 1 time

vinhai@vinhai-desktop$
Reader-Writer Problem
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/types.h>
#include<sys/sem.h>
#include<sys/msg.h>
#define N 10
void writer();
void reader();
void quit(int,int);
int semid,msgid;
main()
{
              int num,ch;
              semid=semget((key_t)0x43,1,IPC_CREAT|0666);
              printf("Semaphore value is %d n",semid);
              msgid=msgget((key_t)43,IPC_CREAT|0666);
              for(;;)
              {
               printf("1. WRITER n");
               printf("2. READER n");
               printf("3. EXit n");
               printf("Enter the choice n");
               scanf("%d",&ch);
               switch(ch)
               {
                      case1:
                             writer();
                             break;
                      case2:
                             reader();
                             break;
                      case3:
                             quit(semid,msgid);
                             break;
                             default:
                                    printf("Wrong Choice n");
               }
               }
}
void writer()
{
      char item[20];
      int num,i;
      struct sembuf sop;
      printf("Writer is in critical section n");
      printf("Enter the num of items to be writtenn");
      scanf("%d",&num);
      if(num<(N-semctl(semid,0,GETVAL,0)))
      {
        sop.sem_num-0;
        sop.sem_op=num;
        sop.sem_flg=0;
        semop(semid,&sop,1);
       for(i=0;i<num;i++)
       {
              printf("Print message[%d]n",i+1);
              scanf("%s",item);
              msgsnd(msgid,&item,strlen(item),IPC_CREAT);
        }
      }
      else
      {
       printf("Cannot write %d message n",num);
       }
      }

void reader()
{
             char item[20];
             int num,i,n1;
             struct sembuf sop;
             printf("Writer is in critical section n");
             printf("Enter the num of items to be written n");
             scanf("%d",&num);
             if(semctl(semid,0,GETVAL,0))>0)
             {
               n1=semctl(semid,0,GETVAL,0);
               printf("The queue has %d items n",n1);
if(num<=n1)
               {
                     sop.sem_num=0;
                     sop.sem_op=num;
                     sop.sem_flg=0;
                     semop(semid,&sop,1);
                     for(i=0;i<num;i++)
                     {
                           msgrcv(msgid,&item,50,0,IPC_CREAT);
                           printf("The item received iw %s n",item);
                     }
                   }
           }
           else
           {
                    printf("There is no message n");
           }

void quit(int semid,int msgid)
{
      semctl(semid,0,IPC_RMID,0);
      msgctl(msgid,IPC_RMID,0);
      exit(0);
}
Output :

vinhai@vinhai-desktop$ gcc rw.c
vinhai@vinhai-desktop$ ./a.out
Semaphore value is 819203
1. WRITER
2. READER
3. EXIT
Enter the choice
1
Writer is in critical section
Enter the num of items to written
2
Enter Message[1] : hai
Enter Message[2] : cst
1. WRITER
2. READER
3. EXIT
Enter the choice
2
reader is in critical section
Enter the num of items to written
1
The queue has 2 items
The item recived is hai
The item recived is cst
1. WRITER
2. READER
3. EXIT
Enter the choice
3
vinhai@vinhai-desktop$
Two Process Mutual Exclusion
#include<stdio.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<sys/types.h>
#include<string.h>
#define key 200
main(0
{
int msgqid,pid;
struct
{
int mtype;
char mtext[30];
}buf;
msgqid=msgget(key,IPC_CREAT|0666);
if(msgqid==-1)
{
printf("Error in the message queue creation");
exit(0);
}
pid=fork();
if(pid==-1)
{
printf("Error in process creation");
exit(1);
}
if(pid==0)
{
strcpy(buf.mtext,"Two process mutual exclusion");
buf.mtype=2;
msgsnd(msgqid,&buf,sizeof(buf.mtext),IPC_NOWAIT);
strcpy(buf.mtext,"Unix program");
buf.mtype=1;
msgsnd(msgqid,&buf,sizeof(buf,mtext),IPC_NOWAIT);
}
else
{
msgrcv(msgqid,&buf,sizeof(buf.mtext),IPC_NOWAIT);
printf("n Message is:%s",buf.mtext);
msgrcv(msgqid,&buf,sizeof(buf,mtext),IPC_NOWAIT);
printf("n Message is:%s",buf.mtext);
}
}

Output :

vinhai@vinhai-desktop$ gcc tpme.c
vinhai@vinhai-desktop$ ./a.out

Msg is:Two Process Mutual Exclusion
Msg is:Unix Program

vinhai@vinhai-desktop$

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (19)

Os lab file c programs
Os lab file c programsOs lab file c programs
Os lab file c programs
 
Cpds lab
Cpds labCpds lab
Cpds lab
 
Program for hamming code using c
Program for hamming code using cProgram for hamming code using c
Program for hamming code using c
 
Cn os-lp lab manual k.roshan
Cn os-lp lab manual k.roshanCn os-lp lab manual k.roshan
Cn os-lp lab manual k.roshan
 
C PROGRAMS
C PROGRAMSC PROGRAMS
C PROGRAMS
 
C
CC
C
 
Data Structures Using C Practical File
Data Structures Using C Practical File Data Structures Using C Practical File
Data Structures Using C Practical File
 
Os lab 1st mid
Os lab 1st midOs lab 1st mid
Os lab 1st mid
 
C programms
C programmsC programms
C programms
 
Assignment no39
Assignment no39Assignment no39
Assignment no39
 
ภาษาซี
ภาษาซีภาษาซี
ภาษาซี
 
ภาษาซี
ภาษาซีภาษาซี
ภาษาซี
 
Python 炒股指南
Python 炒股指南 Python 炒股指南
Python 炒股指南
 
C basics
C basicsC basics
C basics
 
Programs
ProgramsPrograms
Programs
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++
 
C++ file
C++ fileC++ file
C++ file
 
Travel management
Travel managementTravel management
Travel management
 
C Programming lab
C Programming labC Programming lab
C Programming lab
 

Andere mochten auch (12)

Java
JavaJava
Java
 
Advance Java - 2nd Unit
Advance Java - 2nd UnitAdvance Java - 2nd Unit
Advance Java - 2nd Unit
 
1cst
1cst1cst
1cst
 
Os module 2 c
Os module 2 cOs module 2 c
Os module 2 c
 
Datastructure
DatastructureDatastructure
Datastructure
 
MSc CST (5yr Integrated Course ) Syllabus - Madras University
MSc CST (5yr Integrated Course ) Syllabus - Madras UniversityMSc CST (5yr Integrated Course ) Syllabus - Madras University
MSc CST (5yr Integrated Course ) Syllabus - Madras University
 
Ooad
OoadOoad
Ooad
 
Operating System
Operating SystemOperating System
Operating System
 
Mutimedia
MutimediaMutimedia
Mutimedia
 
DDBMS
DDBMSDDBMS
DDBMS
 
Ooad
OoadOoad
Ooad
 
Computer Graphics
Computer GraphicsComputer Graphics
Computer Graphics
 

Ähnlich wie Unix Programs

Ähnlich wie Unix Programs (20)

Os lab upto_1st_mid
Os lab upto_1st_midOs lab upto_1st_mid
Os lab upto_1st_mid
 
Os lab upto 1st mid
Os lab upto 1st midOs lab upto 1st mid
Os lab upto 1st mid
 
C Programming
C ProgrammingC Programming
C Programming
 
C Prog - Pointers
C Prog - PointersC Prog - Pointers
C Prog - Pointers
 
C Programming Example
C Programming ExampleC Programming Example
C Programming Example
 
Ejercicios de programacion
Ejercicios de programacionEjercicios de programacion
Ejercicios de programacion
 
Bankers Algo Implementation
Bankers Algo ImplementationBankers Algo Implementation
Bankers Algo Implementation
 
Program flowchart
Program flowchartProgram flowchart
Program flowchart
 
Program presentation
Program presentationProgram presentation
Program presentation
 
Hargun
HargunHargun
Hargun
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
'C' language notes (a.p)
'C' language notes (a.p)'C' language notes (a.p)
'C' language notes (a.p)
 
DSC program.pdf
DSC program.pdfDSC program.pdf
DSC program.pdf
 
PCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfPCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdf
 
PCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docxPCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docx
 
pattern-printing-in-c.pdf
pattern-printing-in-c.pdfpattern-printing-in-c.pdf
pattern-printing-in-c.pdf
 
Chapter 8 c solution
Chapter 8 c solutionChapter 8 c solution
Chapter 8 c solution
 
Cpd lecture im 207
Cpd lecture im 207Cpd lecture im 207
Cpd lecture im 207
 
งานนำเสนอ อาจารย์ลาวัลย์
งานนำเสนอ อาจารย์ลาวัลย์งานนำเสนอ อาจารย์ลาวัลย์
งานนำเสนอ อาจารย์ลาวัลย์
 
C Programs.pptx
C Programs.pptxC Programs.pptx
C Programs.pptx
 

Unix Programs

  • 1. Unix Lab IPC Using Message Queues #include<stdio.h> #include<sys/ipc.h> #include<string.h> main() { int id; struct { int type; char a[20]; }s; key_t k=984171582; s.type=1; id=msgget(k,IPC_CREAT|0666); strcpy(s.a,"Welcome"); msgsnd(k,s.a,50,0); printf("n Msg sent"); msgrcv(k,&s,50,0,0); printf("n Msg is:%sn",s.a); } Output : vinhai@vinhai-desktop$ gcc ms.c vinhai@vinhai-desktop$ ./a.out Msg sent Msg is:Welcome vinhai@vinhai-desktop$
  • 2. IPC Using Pipes #include<stdio.h> #include<sys/ipc.h> #include<string.h> main() { int id,fd[2]; char s[40]; id=fork(); if(id>0) { printf("n Pareent Process n"); strcpy(s,"n Hello child n"); write(fd[1],s,20); sleep(3); read(fd[0],s,20); printf("n %s",s); } else { printf("n Child Process n"); strcpy(s,"n Hello Parent n"); printf("n Reading Msg:%s",s); write(fd[1],s,20); } } Output : vinhai@vinhai-desktop$ cc ipcp.c vinhai@vinhai-desktop$ ./a.out Child Process Reading Message : Hello Parent Parent Process Hello Child vinhai@vinhai-desktop$
  • 3. IMPLEMENTATION OF WAIT & SIGNAL USING COUNTING SEMAPHORE #include<unistd.h> #include<stdio.h> #include<sys/sem.h> #include<sys/types.h> void wait(int s) { while(semctl(s,0,GETVAL,0)<=0) semctl(s,0,SETVAL,semctl(s,0,GETVAL,0)-1); } void signal(int s) { semctl(s,0,SETVAL,semctl(s,0,GETVAL,0)+1); } int main() { int pid,semid,i; printf("n Implementetion Using Counting Semaphoren"); semid = semget(0x21,1,0666|IPC_CREAT); pid = fork(); wait(semid); printf("nt Process,%d,START[",getpid()); for(i = 0;i<5;i++) { printf((pid ==0?"*" : "#")); fflush(stdout); sleep(1); } printf("]ENDn"); signal(semid); if(pid>0) { wait(0); semctl(semid,0,IPC_RMID,0); } return 0; }
  • 4. Output : vinhai@vinhai-desktop$ cc semc.c vinhai@vinhai-desktop$ ./a.out Implementetion Using Counting Semaphore Process,1714,START[####]END Process,1714,START[****]END vinhai@vinhai-desktop$
  • 5. IMPLEMENTATION OF WAIT & SIGNAL USING BINARY SEMAPHORE #include<stdio.h> #include<sys/types.h> #include<sys/sem.h> main() { int semid,pid; struct sembuf sop; semid = semget((key_t)35,1,IPC_CREAT|0666); pid=fork(); if(pid==0) { sleep(2); printf("Child Before Semop n"); sop.sem_num = 0; sop.sem_op = 0; sop.sem_flg = 0; semop(semid,&sop,1); printf("Child Over n"); } else { printf("Before 1 Semaphore n"); semctl(semid,0,SETVAL,1); Printf("PARENT SLEEPn"); sleep(5); printf("Parent Before 2 Semaphore n"); semctl(semid,0,SETVAL,0); Printf("PARENT Over n"); } } Output : vinhai@vinhai-desktop$ cc semb.c vinhai@vinhai-desktop$ ./a.out Before 1 Semaphore PARENT SLEEP Child Before Semop Parent Before 2 Semaphore PARENT Over Child Over vinhai@vinhai-desktop$
  • 6. AUTOMIC COUNTER UPDATE PROBLEM #include<stdio.h> #include<unistd.h> #include<sys/shm.h> #include<sys/sem.h> #include<sys/ipc.h> #include<sys/types.h> #define key 204 main() { int balance = 500; static struct sembuf unlock[1] = {0,-1,IPC_NOWAIT}; static struct sembuf lock[2] = {0,0,0,0,1,0}; int semid = semget(key,1,IPC_CREAT|0666); int shmid,pid,deposit,withdraw ; void *shmptr; struct shmid_ds myshmid_ds; shmid = shmget(IPC_PRIVATE,1,0666|IPC_CREAT); if(semid<1) { printf(" Semaphore not created "); } pid = fork(); if(pid != 0) { shmptr = shmat(shmid,0,SHM_R); sleep(5); semop(semid,&lock[0],2); balance = *(int *)shmptr; printf("n Enter the With Draw Ammount : Rs. "); scanf("%d",&withdraw); balance = balance-withdraw; printf("n Balance After the With Draw Ammount : Rs. %d",balance);
  • 7. semop(semid,&unlock[0],1); } else { shmptr = shmat(shmid,0,SHM_W); semop(semid,&lock[0],2); printf("n Enter the Deposit Ammount : Rs. "); scanf("%d",&deposit); balance = balance + deposit; *(int *)shmptr = balance; printf("n Balance After Deposit : Rs. %d n",balance); semop(semid,&unlock[0],1); } shmctl(shmid,IPC_RMID,&myshmid_ds); semctl(semid,0,IPC_RMID,0); } Output : vinhai@vinhai-desktop$ cc atomic.c vinhai@vinhai-desktop$ ./a.out Enter the Deposit Ammount : Rs. 1000 Balance After Deposit : Rs. 1500 Enter the With Draw Ammount : Rs. 500 Balance After the With Draw Ammount : Rs. 1000 vinhai@vinhai-desktop$
  • 8. Counting Semaphores At The User Level Using Binary Semaphores #include<stdio.h> #include<unistd.h> #include<sys/sem.h> #include<sys/ipc.h> #include<sys/types.h> #define SEM1 0 #define SEM2 1 #define SEM3 2 int count = 3,semid; struct sembuf wait1 = {SEM1,-1,SEM_UNDO}; struct sembuf signal1 = {SEM1,1,IPC_NOWAIT}; struct sembuf wait2 = {SEM2,-1,SEM_UNDO}; struct sembuf signal2 = {SEM2,1,IPC_NOWAIT}; struct sembuf wait3 = {SEM3,-1,SEM_UNDO}; struct sembuf signal3 = {SEM3,1,IPC_NOWAIT}; main() { int pid; union semun { int val; } mysemum; void countwait(); void countsignal(); semid = semget(IPC_PRIVATE,3,0666|IPC_CREAT); mysemun.val = 1; semctl(semid,SEM1,SETVAL,mysemun); semctl(semid,SEM3,SETVAL,mysemun); mysemun.val = 0; semctl(semid,SEM2,SETVAL,mysemun); pid = fork(); if(pid != 0) { countwait(); countwait(); countwait(); countsignal(); countwait(); countsignal();
  • 9. countsignal(); countsignal(); countwait(); countsignal(); } } void countwait() { semop(semid,&wait3,1); semop(semid,&wait1,1); count = count -1; printf("n Counting Semaphore After Wait is : %d",count); if(count<0) { printf("n Counting Semaphore less than zero "); printf("n sSem1 : Signal1"); semop(semid,&signal1,1); printf("n sSem2 : wait"); } else { semop(semid,&signal1,1); semop(semid,&signal1,1); } } void countsignal() { semop(semid,&wait1,1); count = count +1; printf("n Value of Counting Semaphore After Signal is : %d",count); if(count<=0) { semop(semid,&signal2,1); printf("n Semaphore Count less than zero signaling sem1 &sem3"); } semop(semid,&signal1,1); semop(semid,&signal1,1); }
  • 10. Output : vinhai@vinhai-desktop$ cc csem.c vinhai@vinhai-desktop$ ./a.out Counting Semaphore After Wait is : 2 Counting Semaphore After Wait is : 1 Counting Semaphore After Wait is : 0 Value of Counting Semaphore After Signal is : 1 Value of Counting Semaphore After Signal is : 1 Value of Counting Semaphore After Signal is : 2 Value of Counting Semaphore After Signal is : 3 Counting Semaphore After Wait is : 2 Value of Counting Semaphore After Signal is : 3 vinhai@vinhai-desktop$
  • 11. SIGNALING PROCESS #include<stdio.h> #include<signal.h> void s() { printf("n This is my signal"); } main() { printf("n Before signal"); signal(SIGALRM,s); alarm(2); pause(); printf("n After Signal n "); } OUTPUT : vinhai@vinhai-desktop$ cc si.c vinhai@vinhai-desktop$ ./a.out Before signal This is my signal After Signal vinhai@vinhai-desktop$
  • 12. DEADLOCK DETECTION #include<stdio.h> #include<stdlib.h> main() { int i,n,j,al[10],re[10]; printf("enter the no process : "); scanf("%d",&n); for(i=1;i<=n;i++) { printf("enter the resourse allocated and need for process : %d ",i," "); scanf("%d%d",&re[i],&al[i]); } for(i=1;i<=n;i++) { for(i=j;j<=n;j++) { if(re[i]==al[j]) { printf("p%d is deadlock because r%d allocated for : p%d",i,re[i],j); exit(0); } } } } OUTPUT : vinhai@vinhai-desktop$ cc deadlock.c vinhai@vinhai-desktop$ ./a.out enter the no process : 2 enter the resourse allocated and need for process : 1 1 2 enter the resourse allocated and need for process : 2 2 1 Segmentation fault vinhai@vinhai-desktop$
  • 13. PROCESS SCHEDULING (FCFS) #include<stdio.h> main() { int i,n,t=0,s=0,b[10],t1; printf("n enter the no of values : "); scanf("%d",&n); printf("n enter the times : "); for(i=0;i<n;i++) scanf("%d",&b[i]); printf("ntprocesstttimettstartttendttwait"); for(i=0;i<n;i++) { s=s+b[i]; printf("nt%dtt%dtt%dtt%dtt%d",i+1,b[i],t,s,t); t1=t; t=s; } printf("n avg time%dn",s/n); printf("b avg waiting time %d n",t1/n); } OUTPUT : vinhai@vinhai-desktop$ cc fcfs.c vinhai@vinhai-desktop$ ./a.out enter the no of values : 2 enter the times : 1 3 process time start end wait 1 1 0 1 0 2 3 1 4 1 avg time 2 avg waiting time 0 vinhai@vinhai-desktop$
  • 14. PROCESS SCHEDULING (LEAST FREQUENTLY USED) #include<stdio.h> main() { int i,j,n,t,a[10],s=0,e=0; printf("n Enter the n value : "); scanf("%d",&n); printf("n Enter the s value : "); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(a[i]>a[j]) { t=a[i]; a[i]=a[j]; a[j]=t; } }} printf("n Process Time Start End Wait "); for(i=0;i<n;i++) { s=s+a[i]; printf("n %dt%dt%dt%dt%d n ",i+1,a[i],e,s,e); e=s; } } OUTPUT : vinhai@vinhai-desktop$ gcc i.c vinhai@vinhai-desktop$ ./a.out Enter the n value3 Enter the s value2 3 4 Process Time Start End Wait 1 1 0 1 0 2 2 1 3 1 3 3 3 6 3 vinhai@vinhai-desktop$
  • 15. PROCESS SCHEDULING (ROUND ROBIN) #include<stdio.h> main() { int i,a[10],n,ts,t=0; printf("n Enter the Process & Time-Slice : "); scanf("%d %d",&n,&ts); printf("n Enter the Time "); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("n Process Time : "); st: t=0; for(i=0;i<n;i++) { if(a[i]>=ts) { a[i]=a[i]-ts; printf("n %d %d n",i+1,ts); t++; } else if(a[i]!=0) { printf("n %d %d n ",i+1,a[i]); a[i]=0; }} if(t>0) goto st; } OUTPUT : vinhai@vinhai-desktop$ cc rr.c vinhai@vinhai-desktop$ ./a.out Enter the Process & Time-Slice : 2 2 Enter the Time 3 1 Process Time : 1 2 2 1 1 1 vinhai@vinhai-desktop$
  • 16. PRODUCER CONSUMER PROBLEM WITH LIMITED BUFFERS #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #include<sys/shm.h> #define NELEN 4 #define SEMPTY 0 #define SFULL 1 main() { int pid,semid,shmid,status,i; char elem; union semun { int val; }mysemnum; struct sembuf waitempty={SEMPTY,-1,SEM_UNDO}; struct sembuf signalempty={SEMPTY,1,IPC_NOWAIT}; struct sembuf waitfull={SFULL,-1,SEM_UNDO}; struct sembuf signalfull={SFULL,1,IPC_NOWAIT}; struct shmid_ds myshmid_ds; void *shmptr; semid = semget(IPC_CREAT|0666,IPC_PRIVATE<2); if(semid<0) { printf("Semop Creation Error n"); } mysemnum.val=NELEN; semctl(semid,SEMPTY,SETVAL,mysemnum); mysemnum.val=0; semctl(semid,SFULL,SETVAL,mysemnum); shmid=shmgat(IPC_PRIVATE,NELEN,0666|IPC_CREAT);
  • 17. if(shmid<0) { printf("Shared Memory Errorn"); } pid=fork(); if(pid<0) { printf("Proccess Creation Errorn"); } if(pid==0) { shmptr=shmat(shmid,0,SHM_R); for(i=0;i<4;i++) { semop(semid,&waitfull,1); elem=*((char *)shmptr+(i%NELEN)); printf("Consumed Element : %c n",elem); semop(semid,&signalempty,1); sleep(1); } } else { shmptr=shmat(shmid,0,SHM_W); for(i=0;i<4;i++) { semop(semid,&waitempty,1); elem='a'+i; printf("Consumed Element : %c n",elem); *((char *)shmptr+(i%NELEN))=elem; semop(semid,&signalfull,1); sleep(1); } } wait(& status); shmctl(shmid,IPC_RMID,&myshmid_ds); semctl(semid,SEMPTY,IPC_RMID,&mysemnum); }
  • 18. OUTPUT : vinhai@vinhai-desktop$ cc prod.c vinhai@vinhai-desktop$ ./a.out Prodced Element : a Consumed Element : a Prodced Element : a Consumed Element : a Prodced Element : a Consumed Element : a Prodced Element : a Consumed Element : a Prodced Element : a Consumed Element : a vinhai@vinhai-desktop$
  • 19. DINING PHILOSOPHER PROBLEM #include<stdio.h> #include<stdlib.h> #include<unistd.h> #define N 3 #define EATING 1 #define THINKING 1 #define left(p) (p) #define right(p) ((P)+1%N) typedef int *Semaphore; Semaphore spoon[N]; void philosopher(int me); void pick_up(int me); void pick_down(int me); void signal(Semaphore s) int main() { system("clear"); int i,n; for(i=0;i<N;i++) { spoon[i]=make_sema(); signal(spoon[i]); } for(i=0;i<n;i++) { if(fork()==0) break; philosopher(i); } return 0; } void philosopher(int me) { char *s; int i; for(i=1;i<2;i++) { pick_up(me); printf("Philosopher %d eating for th time n",me,i);
  • 20. sleep(EATING); pick_down(me); printf("Philosopher %d eating for th time n",me,i); sleep(THINKING); } } void pick_up(int me) { if(me==0) { wait(spoon[right(me)]); printf("Philosopher %d picks up right spoon n",me); sleep(1); wait(spoon[left(me)]); printf("Philosopher %d picks up right spoon n",me); } else { wait(spoon[left(me)]); printf("Philosopher %d picks up right spoon n",me); } } void pick_down(int me) { signal(spoon[left(me)]); signal(spoon[right(me)]); } void signal(Semaphore s) { if(write(s[1],"x",1)<=0) { printf("Error ! Write() failed, check semaphore creation n"); exit(1); } }
  • 21. void wait(Semaphore s) { int junk; if(read(s[0],&junk,1)<=0) { printf("Error ! Write() failed, check semaphore creation n"); exit(1); } } Semaphore make_sema(void) { int *sema; sema = (int *)calloc(2,siyeof(int)); pipe(sema); return sema; } OUTPUT : vinhai@vinhai-desktop$ cc phil.c vinhai@vinhai-desktop$ ./a.out Philosopher 0 picks up right spoon Philosopher 0 picks up left spoon Philosopher 0 eating for the 1 time Philosopher 0 thnking for the 1 time Philosopher 1 picks up right spoon Philosopher 1 picks up left spoon Philosopher 1 eating for the 1 time Philosopher 1 thnking for the 1 time Philosopher 2 picks up right spoon Philosopher 2 picks up left spoon Philosopher 2 eating for the 1 time Philosopher 2 thnking for the 1 time vinhai@vinhai-desktop$
  • 22. Reader-Writer Problem #include<stdio.h> #include<sys/ipc.h> #include<sys/types.h> #include<sys/sem.h> #include<sys/msg.h> #define N 10 void writer(); void reader(); void quit(int,int); int semid,msgid; main() { int num,ch; semid=semget((key_t)0x43,1,IPC_CREAT|0666); printf("Semaphore value is %d n",semid); msgid=msgget((key_t)43,IPC_CREAT|0666); for(;;) { printf("1. WRITER n"); printf("2. READER n"); printf("3. EXit n"); printf("Enter the choice n"); scanf("%d",&ch); switch(ch) { case1: writer(); break; case2: reader(); break; case3: quit(semid,msgid); break; default: printf("Wrong Choice n"); } } }
  • 23. void writer() { char item[20]; int num,i; struct sembuf sop; printf("Writer is in critical section n"); printf("Enter the num of items to be writtenn"); scanf("%d",&num); if(num<(N-semctl(semid,0,GETVAL,0))) { sop.sem_num-0; sop.sem_op=num; sop.sem_flg=0; semop(semid,&sop,1); for(i=0;i<num;i++) { printf("Print message[%d]n",i+1); scanf("%s",item); msgsnd(msgid,&item,strlen(item),IPC_CREAT); } } else { printf("Cannot write %d message n",num); } } void reader() { char item[20]; int num,i,n1; struct sembuf sop; printf("Writer is in critical section n"); printf("Enter the num of items to be written n"); scanf("%d",&num); if(semctl(semid,0,GETVAL,0))>0) { n1=semctl(semid,0,GETVAL,0); printf("The queue has %d items n",n1);
  • 24. if(num<=n1) { sop.sem_num=0; sop.sem_op=num; sop.sem_flg=0; semop(semid,&sop,1); for(i=0;i<num;i++) { msgrcv(msgid,&item,50,0,IPC_CREAT); printf("The item received iw %s n",item); } } } else { printf("There is no message n"); } void quit(int semid,int msgid) { semctl(semid,0,IPC_RMID,0); msgctl(msgid,IPC_RMID,0); exit(0); }
  • 25. Output : vinhai@vinhai-desktop$ gcc rw.c vinhai@vinhai-desktop$ ./a.out Semaphore value is 819203 1. WRITER 2. READER 3. EXIT Enter the choice 1 Writer is in critical section Enter the num of items to written 2 Enter Message[1] : hai Enter Message[2] : cst 1. WRITER 2. READER 3. EXIT Enter the choice 2 reader is in critical section Enter the num of items to written 1 The queue has 2 items The item recived is hai The item recived is cst 1. WRITER 2. READER 3. EXIT Enter the choice 3 vinhai@vinhai-desktop$
  • 26. Two Process Mutual Exclusion #include<stdio.h> #include<unistd.h> #include<sys/ipc.h> #include<sys/msg.h> #include<sys/types.h> #include<string.h> #define key 200 main(0 { int msgqid,pid; struct { int mtype; char mtext[30]; }buf; msgqid=msgget(key,IPC_CREAT|0666); if(msgqid==-1) { printf("Error in the message queue creation"); exit(0); } pid=fork(); if(pid==-1) { printf("Error in process creation"); exit(1); } if(pid==0) { strcpy(buf.mtext,"Two process mutual exclusion"); buf.mtype=2; msgsnd(msgqid,&buf,sizeof(buf.mtext),IPC_NOWAIT); strcpy(buf.mtext,"Unix program"); buf.mtype=1; msgsnd(msgqid,&buf,sizeof(buf,mtext),IPC_NOWAIT); }
  • 27. else { msgrcv(msgqid,&buf,sizeof(buf.mtext),IPC_NOWAIT); printf("n Message is:%s",buf.mtext); msgrcv(msgqid,&buf,sizeof(buf,mtext),IPC_NOWAIT); printf("n Message is:%s",buf.mtext); } } Output : vinhai@vinhai-desktop$ gcc tpme.c vinhai@vinhai-desktop$ ./a.out Msg is:Two Process Mutual Exclusion Msg is:Unix Program vinhai@vinhai-desktop$