· 7 years ago · Oct 05, 2018, 04:44 AM
1Orphan Process
2/*
3* Program to create orphan process @ Linux
4* getpid() gives process PID and
5* getppid() gives process's parent ID
6* here main() process ID is parent id is current shells PID
7* once process becomes orphan it is adopted by init process(it's PID is 1)
8*/
9#include<stdio.h>
10#include<unistd.h>
11int main()
12{
13pid_t p;
14/* create child process */
15p=fork();
16if(p==0) {
17/* fork() returns Zero to child */
18sleep(10);
19}
20printf("The child process pid is %d parent pid %d\n", getpid(), getppid());
21/*parent/child waits for 20 secs and exits*/
22sleep(20);
23printf("\nProcess %d is done its Parent pid %d...\n", getpid(), getppid());
24return 0;
25}
26O/p
27$ ./a.out
28The child process pid is 2575 parent pid 1922
29The child process pid is 2576 parent pid 2575
30Process 2575 is done its Parent pid 1922...
31$ ./a.out
32Process 2576 is done its Parent pid 1...
33M.NAGARAJU, SCOPE,VIT VELLORE Page 3
34Zombie Process
35• // Child becomes Zombie as parent is sleeping. when child process exits.
36#include <stdio.h>
37#include <stdlib.h>
38#include <sys/types.h>
39#include <unistd.h>
40int main()
41{
42// Fork returns process id. // in parent process.
43pid_t child_pid = fork(); // Parent process.
44if (child_pid > 0) {
45sleep(50);printf("Finally Parent with id = %d awakens whose child with id=%d already
46existed\n",getpid(),child_pid);
47}
48else
49{
50// Child process
51printf("Child process with id = %d exists while its parent with id =%d is still sleeping
52\n",getpid(),getppid());
53printf("Thus child with id=%d becomes zombie now\n",getpid());
54exit (0);
55}
56return 0;
57Daemon Process
58#include <stdio.h>
59#include <stdlib.h>
60#include <sys/types.h>
61#include <unistd.h>
62int main()
63{
64int pid=fork();
65if (pid<0) { printf("Fork Error "); exit(1);} /* fork error */
66if (pid>0) { printf("Parent exists");exit(0); }/* parent exits */
67printf("Child continues at the background as daemon");
68/* child (daemon) continues */
69return 0;
70}
71
72
731.Predict the Output of the following program.
74#include<stdio.h>
75#include<sys/types.h>
76#include<unistd.h>
77int main() {
78
79 // make two process which run same
80 // program after this instruction
81 fork();
82
83 printf("Hello world! %d\n", getpid());
84 return 0;
85}
86Output:
87Hello world!
88Hello world!
89
902. Calculate number of times hello is printed.
91#include <stdio.h>
92#include <sys/types.h>
93int main()
94{
95 fork();
96 fork();
97 fork();
98 printf("hello %d\n ", getpid());
99 return 0;
100}
101Output:
102hello
103hello
104hello
105hello
106hello
107hello
108hello
109hello
110fork (); // Line 1
111fork (); // Line 2
112fork (); // Line 3
113
114 L1 // There will be 1 child process
115 / \ // created by line 1.
116 L2 L2 // There will be 2 child processes
117 / \ / \ // created by line 2
118L3 L3 L3 L3 // There will be 4 child processes
119 // created by line 3
120
121So there are total eight processes (new child processes and one original process)
122
1233. Predict the Output of the following program
124#include<stdio.h>
125#include <sys/types.h>
126#include<unistd.h>
127void forkexample()
128{
129 // child process because return value zero
130 if (fork()==0)
131 printf("Hello from Child! %d\n", getpid());
132
133 // parent process because return value non-zero.
134 else
135 printf("Hello from Parent!%d\n", getppid());
136}
137int main()
138{
139 forkexample();
140 return 0;
141}
142Output:
1431.
144Hello from Child!
145Hello from Parent!
146 (or)
1472.
148Hello from Parent!
149Hello from Child!
150In the above code, a child process is created, fork() returns 0 in the child process and positive integer to the parent process.
151Here, two outputs are possible because parent process and child process are running concurrently. So we don’t know if OS first give control to which process a parent process or a child process.
152
153Important: Parent process and child process are running same program, but it does not mean they are identical. OS allocate different data and state for these two processes and also control flow of these processes can be different. See next example
154
1554. Predict the Output of the following program.
156#include<stdio.h>
157#include<sys/types.h>
158#include<unistd.h>
159
160void forkexample()
161{
162 int x = 1;
163
164 if (fork() == 0)
165 printf("%d Child has x = %d\n", getpid(),++x);
166 else
167 printf("%d Parent has x = %d\n", getppid(),--x);
168}
169int main()
170{
171 forkexample();
172 return 0;
173}
174Output:
1751. Parent has x = 0
1762. Child has x = 2
1773. (or)
1784. Child has x = 2
1795. Parent has x = 0
180
181
182exec family of functions in C
183
184The exec family of functions replaces the current running process with a new process. It can be used to run a C program by using another C program. It comes under the header file unistd.h. There are many members in the exec family which are shown below with examples.
185ï‚§ execvp: Using this command, the created child process does not have to run the same program as the parent process does. The exec type system calls allow a process to run any program files, which include a binary executable or a shell script. Syntax:
186int execvp (const char *file, char *const argv[]);
187file: points to the file name associated with the file being executed.
188argv: is a null terminated array of character pointers.
189Let us see a small example to show how to use execvp() function in C. We will have two .C files, EXEC.c and execDemo.c and we will replace the execDemo.c with EXEC.c by calling execvp() function in execDemo.c .
190//EXEC.c
191
192#include<stdio.h>
193#include<unistd.h>
194
195int main()
196{
197 int i;
198
199 printf("I am EXEC.c called by execvp() ");
200 printf("\n");
201
202 return 0;
203}
204
205Now, create an executable file of EXEC.c using command
206gcc EXEC.c -o EXEC
207//execDemo.c
208
209#include<stdio.h>
210#include<stdlib.h>
211#include<unistd.h>
212int main()
213{
214 //A null terminated array of character
215 //pointers
216 char *args[]={"./EXEC",NULL};
217 execvp(args[0],args);
218
219 /*All statements are ignored after execvp() call as this whole
220 process(execDemo.c) is replaced by another process (EXEC.c)
221 */
222 printf("Ending-----");
223
224 return 0;
225}
226
227Now, create an executable file of execDemo.c using command
228
229gcc execDemo.c -o execDemo
230After running the executable file of execDemo.c by using command ./excDemo, we get the following output:
231I am EXEC.c called by execvp()
232When the file execDemo.c is compiled, as soon as the statement execvp(args[0],args) is executed, this very program is replaced by the program EXEC.c. “Ending—–†is not printed because because as soon as the execvp() function is called, this program is replaced by the program EXEC.c.
233ï‚§ execv : This is very similar to execvp() function in terms of syntax as well. The syntax of execv() is as shown below:Syntax:
234int execv(const char *path, char *const argv[]);
235path: should point to the path of the file being executed.
236argv[]: is a null terminated array of character pointers.
237Let us see a small example to show how to use execv() function in C. This example is similar to the example shown above for execvp() . We will have two .C files , EXEC.c and execDemo.cand we will replace the execDemo.c with EXEC.c by calling execv() function in execDemo.c .
238
239
240
241
242
243
244
245
246//EXEC.c
247
248#include<stdio.h>
249#include<unistd.h>
250
251int main()
252{
253 int i;
254
255 printf("I am EXEC.c called by execv() ");
256 printf("\n");
257 return 0;
258}
259
260Now,create an executable file of EXEC.c using command
261gcc EXEC.c -o EXEC
262//execDemo.c
263
264#include<stdio.h>
265#include<stdlib.h>
266#include<unistd.h>
267int main()
268{
269 //A null terminated array of character
270 //pointers
271 char *args[]={"./EXEC",NULL};
272 execv(args[0],args);
273
274 /*All statements are ignored after execvp() call as this whole
275 process(execDemo.c) is replaced by another process (EXEC.c)
276 */
277 printf("Ending-----");
278
279 return 0;
280}
281
282Now, create an executable file of execDemo.c using command
283gcc execDemo.c -o execDemo
284After running the executable file of execDemo.c by using command ./excDemo, we get the following output:
285I am EXEC.c called by execv()
286
287
288
289Program for First Come First Served (FCFS)
290Scheduling Algorithm
291
292#include <stdio.h>
293void fcfs(int ); /* to implement first come first serve scheduling */
294void turn_around(int, int [], int []); /* to calculate turn around time */
295int main()
296{
297static int size; /* size of the queue */
298printf("Enter the total number of processes: ");
299scanf("%d", &size);
300if(size == 0) goto empty_queue; /* no process in the queue */
301fcfs(size); /* first come first serve */
302return 0; /* end of run */
303empty_queue: printf("\nProcess queue is empty. End of run.\n");
304}
305/* fcfs : to implement first come first serve scheduling */
306void fcfs(int size)
307{
308int i, j, result;
309int arrival[size], burst[size], waiting[size];
310for(i=0; i<size; ++i) waiting[i]=0; /* initialize all values with 0 */
311/* input the arrival time and burst time for each process */
312for(i=0; i<size; ++i) {
313printf("\nEnter arrival time for process %d : ", i+1);
314scanf("%d", &arrival[i]);
315printf("Enter burst time for process %d : ", i+1);
316scanf("%d", &burst[i]);
317}
318/* first come first serve */
319for(i=1; i<size; ++i) {
320result=0;
321for(j=0; j<i; ++j) result+= burst[j];
322waiting[i]=result - arrival[i];
323/* waiting time = starting time - arrival time */
324}
325/* print the waiting time */
326printf("\nWaiting Time:\t");
327for(i=0; i<size; ++i)
328printf("%d\t", waiting[i]);
329/* average waiting time */
330for(i=0; i<size; ++i) result+=waiting[i];
331result/=size;
332printf("\nAverage Waiting Time:\t%d", result);
333/* turn around time */
334turn_around(size, burst, waiting);
335printf("\n");
336}
337/* turn_around : to calculate turn around time for each process */
338void turn_around(int size, int burst[], int waiting[])
339{
340int i;
341int turn_around_time[size];
342for(i=0; i<size; ++i)
343turn_around_time[i]= burst[i] + waiting[i]; /* turn around time = burst
344time + waiting time */
345printf("\nTurn Around Time:\t");
346for(i=0; i<size; ++i)
347printf("%d\t", turn_around_time[i]);
348}
349
350
351C Program for Shortest Job First (SJF)
352Scheduling Algorithm (NON-PREEMPTIVE)
353
354#include<stdio.h>
355void main()
356{
357int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
358float avg_wt,avg_tat;
359printf("Enter number of process:");
360scanf("%d",&n);
361printf("\nEnter Burst Time:\n");
362for(i=0;i<n;i++)
363{
364printf("p%d:",i+1);
365scanf("%d",&bt[i]);
366p[i]=i+1; //contains process number
367}
368//sorting burst time in ascending order using selection sort
369for(i=0;i<n;i++)
370{
371pos=i;
372for(j=i+1;j<n;j++)
373{
374if(bt[j]<bt[pos])
375pos=j;
376}
377temp=bt[i];
378bt[i]=bt[pos];
379bt[pos]=temp;
380temp=p[i];
381p[i]=p[pos];
382p[pos]=temp;
383}
384wt[0]=0; //waiting time for first process will be zero
385//calculate waiting time
386for(i=1;i<n;i++)
387{
388wt[i]=0;
389for(j=0;j<i;j++)
390wt[i]+=bt[j];
391total+=wt[i];
392}
393avg_wt=(float)total/n; //average waiting time
394total=0;
395printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");
396for(i=0;i<n;i++)
397{
398tat[i]=bt[i]+wt[i]; //calculate turnaround time
399total+=tat[i];
400printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
401}
402avg_tat=(float)total/n; //average turnaround time
403printf("\n\nAverage Waiting Time=%f",avg_wt);
404printf("\nAverage Turnaround Time=%f\n",avg_tat);
405
406}
407
408C Program for Shortest Job First (SJF)
409Scheduling Algorithm (PREEMPTIVE)-SRTF
410
411#include <stdio.h>
412int main()
413{
414int arrival_time[10], burst_time[10], temp[10];
415int i, smallest, count = 0, time, limit;
416double wait_time = 0, turnaround_time = 0, end;
417float average_waiting_time, average_turnaround_time;
418printf("\nEnter the Total Number of Processes:\t");
419scanf("%d", &limit);
420printf("\nEnter Details of %d Processes\n", limit);
421for(i = 0; i < limit; i++)
422{
423printf("\nEnter Arrival Time:\t");
424scanf("%d", &arrival_time[i]);
425printf("Enter Burst Time:\t");
426scanf("%d", &burst_time[i]);
427temp[i] = burst_time[i];
428}
429burst_time[9] = 9999;
430for(time = 0; count != limit; time++)
431{
432smallest = 9;
433for(i = 0; i < limit; i++)
434{
435if(arrival_time[i] <= time && burst_time[i] < burst_time[smallest] && burst_time[i] > 0)
436{
437smallest = i;
438}
439}
440burst_time[smallest]--;
441if(burst_time[smallest] == 0)
442{
443count++;
444end = time + 1;
445wait_time = wait_time + end - arrival_time[smallest] - temp[smallest];
446turnaround_time = turnaround_time + end - arrival_time[smallest];
447}
448}
449average_waiting_time = wait_time / limit;
450average_turnaround_time = turnaround_time / limit;
451printf("\n\nAverage Waiting Time:\t%lf\n", average_waiting_time);
452printf("Average Turnaround Time:\t%lf\n", average_turnaround_time);
453return 0;
454}
455
456C Program for PRIORITY Scheduling
457Algorithm
458
459#include<stdio.h>
460int main()
461{
462int p[30],pr[30],key,loc,bt[30],temp,max,wt[30],ta[30],sum=0,i,j,n;
463wt[0]=0;
464printf("enter the number of processes=");
465scanf("%d",&n);
466printf("enter the burst time for each process");
467for(i=0;i<n;i++)
468{
469p[i]=i+1;
470printf("\np%d=",i+1);
471scanf("%d",&bt[i]);
472printf("\t priority of p%d=",i+1);
473scanf("%d",&pr[i]);
474}
475for(i=0;i<n;i++)
476{ max=i;
477for(j=i+1;j<n;j++)
478{
479if(pr[j] <pr[max])
480max=j;
481}
482temp=pr[max];
483pr[max]=pr[i];
484pr[i]=temp;
485temp=bt[max];
486bt[max]=bt[i];
487bt[i]=temp;
488temp=p[max];
489p[max]=p[i];
490p[i]=temp;
491}
492for(i=0;i<n;i++)
493{ wt[i+1]=bt[i]+wt[i];
494ta[i]=bt[i]+wt[i];
495sum+=ta[i];
496}
497for(i=0;i<n;i++)
498{
499printf("\n waiting time for p[%d]=%d",p[i],wt[i]);
500printf("\t turn around time for p[%d]=%d",p[i],ta[i]);
501}
502printf("\n\n average turn around=%d",sum/n);
503return 1;
504}
505
506OR
507
508#include<stdio.h>
509int main()
510{
511int burst_time[20], process[20], waiting_time[20],
512turnaround_time[20], priority[20];
513int i, j, limit, sum = 0, position, temp;
514float average_wait_time, average_turnaround_time;
515printf("Enter Total Number of Processes:\t");
516scanf("%d", &limit);
517printf("\nEnter Burst Time and Priority For %d Processes\n",
518limit);
519for(i = 0; i < limit; i++)
520{
521printf("\nProcess[%d]\n", i + 1);
522printf("Process Burst Time:\t");
523scanf("%d", &burst_time[i]);
524printf("Process Priority:\t");
525scanf("%d", &priority[i]);
526process[i] = i + 1;
527}
528for(i = 0; i < limit; i++)
529{
530position = i;
531for(j = i + 1; j < limit; j++)
532{
533if(priority[j] < priority[position])
534{
535position = j;
536}
537}
538temp = priority[i];
539priority[i] = priority[position];
540priority[position] = temp;
541temp = burst_time[i];
542burst_time[i] = burst_time[position];
543burst_time[position] = temp;
544temp = process[i];
545process[i] = process[position];
546process[position] = temp;
547}
548waiting_time[0] = 0;
549for(i = 1; i < limit; i++)
550{
551waiting_time[i] = 0;
552for(j = 0; j < i; j++)
553{
554waiting_time[i] = waiting_time[i] + burst_time[j];
555}
556sum = sum + waiting_time[i];
557}
558average_wait_time = sum / limit;
559sum = 0;
560printf("\nProcess ID\t\tBurst Time\t Waiting Time\t Turnaround
561Time\n");
562for(i = 0; i < limit; i++)
563{
564turnaround_time[i] = burst_time[i] + waiting_time[i];
565sum = sum + turnaround_time[i];
566printf("\nProcess[%d]\t\t%d\t\t %d\t\t %d\n", process[i],
567burst_time[i], waiting_time[i], turnaround_time[i]);
568}
569average_turnaround_time = sum / limit;
570printf("\nAverage Waiting Time:\t%f", average_wait_time);
571printf("\nAverage Turnaround Time:\t%f\n",
572average_turnaround_time);
573return 0;
574
575
576
577C Program for round robin Scheduling
578Algorithm
579
580#include<stdio.h>
581int main()
582{
583int count,j,n,time,remain,flag=0,time_quantum;
584int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10];
585printf("Enter Total Process:\t ");
586scanf("%d",&n);
587remain=n;
588for(count=0;count<n;count++)
589{
590printf("Enter Arrival Time and Burst Time for Process Process Number %d :",count+1);
591scanf("%d",&at[count]);
592scanf("%d",&bt[count]);
593rt[count]=bt[count];
594}
595printf("Enter Time Quantum:\t");
596scanf("%d",&time_quantum);
597printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
598for(time=0,count=0;remain!=0;)
599{
600if(rt[count]<=time_quantum && rt[count]>0)
601{
602time+=rt[count];
603rt[count]=0;
604flag=1;
605}
606else if(rt[count]>0)
607{
608rt[count]-=time_quantum;
609time+=time_quantum;
610}
611if(rt[count]==0 && flag==1)
612{
613remain--;
614printf("P[%d]\t|\t%d\t|\t%d\n",count+1,time-at[count],time-at[count]-bt[count]);
615wait_time+=time-at[count]-bt[count];
616turnaround_time+=time-at[count];
617flag=0;
618}
619if(count==n-1)
620count=0;
621else if(at[count+1]<=time)
622count++;
623else
624count=0;
625}
626printf("\nAverage Waiting Time= %f\n",wait_time*1.0/n);
627printf("Avg Turnaround Time = %f",turnaround_time*1.0/n);
628return 0;
629}
630
631C Program for preemptive priority
632Scheduling Algorithm
633
634#include<stdio.h>
635struct process
636{
637char process_name;
638int arrival_time, burst_time, ct, waiting_time, turnaround_time, priority;
639int status;
640}process_queue[10];
641int limit;
642void Arrival_Time_Sorting()
643{
644struct process temp;
645int i, j;
646for(i = 0; i < limit - 1; i++)
647{
648for(j = i + 1; j < limit; j++)
649{
650if(process_queue[i].arrival_time > process_queue[j].arrival_time)
651{
652temp = process_queue[i];
653process_queue[i] = process_queue[j];
654process_queue[j] = temp;
655}
656}
657}
658}
659void main()
660{
661int i, time = 0, burst_time = 0, largest;
662char c;
663float wait_time = 0, turnaround_time = 0, average_waiting_time, average_turnaround_time;
664printf("\nEnter Total Number of Processes:\t");
665scanf("%d", &limit);
666for(i = 0, c = 'A'; i < limit; i++, c++)
667{
668process_queue[i].process_name = c;
669printf("\nEnter Details For Process[%C]:\n", process_queue[i].process_name);
670printf("Enter Arrival Time:\t");
671scanf("%d", &process_queue[i].arrival_time );
672printf("Enter Burst Time:\t");
673scanf("%d", &process_queue[i].burst_time);
674printf("Enter Priority:\t");
675scanf("%d", &process_queue[i].priority);
676process_queue[i].status = 0;
677burst_time = burst_time + process_queue[i].burst_time;
678}
679Arrival_Time_Sorting();
680process_queue[9].priority = -9999;
681printf("\nProcess Name\tArrival Time\tBurst Time\tPriority\tWaiting Time");
682for(time = process_queue[0].arrival_time; time < burst_time;)
683{
684largest = 9;
685for(i = 0; i < limit; i++)
686{
687if(process_queue[i].arrival_time <= time && process_queue[i].status != 1 &&
688process_queue[i].priority > process_queue[largest].priority)
689{
690largest = i;
691}
692}
693time = time + process_queue[largest].burst_time;
694process_queue[largest].ct = time;
695process_queue[largest].waiting_time = process_queue[largest].ct - process_queue[largest].arrival_time
696- process_queue[largest].burst_time;
697process_queue[largest].turnaround_time = process_queue[largest].ct -
698process_queue[largest].arrival_time;
699process_queue[largest].status = 1;
700wait_time = wait_time + process_queue[largest].waiting_time;
701turnaround_time = turnaround_time + process_queue[largest].turnaround_time;
702printf("\n%c\t\t%d\t\t%d\t\t%d\t\t%d", process_queue[largest].process_name,
703process_queue[largest].arrival_time, process_queue[largest].burst_time, process_queue[largest].priority,
704process_queue[largest].waiting_time);
705}
706average_waiting_time = wait_time / limit;
707average_turnaround_time = turnaround_time / limit;
708printf("\n\nAverage waiting time:\t%f\n", average_waiting_time);
709printf("Average Turnaround Time:\t%f\n", average_turnaround_time);
710}
711
712
713BANKERS ALGORITHM
714#include<stdio.h>
715#include<process.h>
716#include<conio.h>
717void main()
718{
719int allocation[10][5],max[10][5],need[10][5],available[3],flag[10],sq[10];
720int n,r,i,j,k,count,count1=0;
721clrscr();
722printf("\n Input the number of processes running ( <10 )..");
723scanf("%d",&n);
724for(i=0;i<10;i++)
725 flag[i]=0;
726printf("\n Input the number of resources ( <5 )..");
727scanf("%d",&r);
728printf("\n Input the allocation matrix for the processes in row major order..\n");
729for(i=0;i<n;i++)
730{
731 printf("\n Process %d\n",i);
732 for(j=0;j<r;j++)
733 {
734 printf("\n Resource %d\n",j);
735 scanf("%d",&allocation[i][j]);
736 }
737}
738printf("\n Input the no. of resources that a process can maximum have..\n");
739for(i=0;i<n;i++)
740{
741 printf("\n Process %d\n",i);
742 for(j=0;j<r;j++)
743 {
744 printf("\n Resource %d\n",j);
745 scanf("%d",&max[i][j]);
746 }
747}
748printf("\n Input the no. of available instances of each resource..\n");
749for(i=0;i<r;i++)
750{
751 printf("\n Resource %d : ",i);
752 scanf("%d",&available[i]);
753}
754printf("\n The need matrix is as follows : \n");
755for(i=0;i<n;i++)
756{
757 for(j=0;j<r;j++)
758 {
759 need[i][j]= max[i][j]-allocation[i][j];
760 printf("\t %d",need[i][j]);
761 }
762 printf("\n");
763}
764do{
765 for(k=0;k<n;k++)
766 {
767 for(i=0;i<n;i++)
768 {
769 if(flag[i]==0)
770 {
771 count=0;
772 for(j=0;j<r;j++)
773 {
774 if(available[j]>=need[i][j])
775 count++;
776 }
777 if(count==r)
778 {
779 count1++;
780 flag[i]=1;
781 sq[count1-1]=i;
782 for(j=0;j<r;j++)
783 {
784 available[j]=available[j]+allocation[i][j];
785 }
786 break;
787 }
788 }
789 }
790 }
791 if(count1!=n)
792 {
793 printf("\n---------------IT'S AN UNSAFE STATE---------------");
794 break;
795 }
796}while(count1!=n);
797if(count1==n)
798{
799 printf("\n *******************IT'S A SAFE STATE*******************");
800 printf("\n The safe sequence is....\n");
801 for(i=0;i<n;i++)
802 printf("\t P%d",sq[i]);
803 printf("\n");
804 printf("\n The available matrix is now : ");
805 for(i=0;i<r;i++)
806 printf("\t %d",available[i]);
807}
808getch();
809}
810
811Or
812
813#include <stdio.h>
814int curr[5][5], maxclaim[5][5], avl[5];
815int alloc[5] = {0, 0, 0, 0, 0};
816int maxres[5], running[5], safe=0;
817int count = 0, i, j, exec, r, p, k = 1;
818
819int main()
820{
821 printf("\nEnter the number of processes: ");
822 scanf("%d", &p);
823
824 for (i = 0; i < p; i++) {
825 running[i] = 1;
826 count++;
827 }
828
829 printf("\nEnter the number of resources: ");
830 scanf("%d", &r);
831
832 for (i = 0; i < r; i++) {
833 printf("\nEnter the resource for instance %d: ", k++);
834 scanf("%d", &maxres[i]);
835 }
836
837 printf("\nEnter maximum resource table:\n");
838 for (i = 0; i < p; i++) {
839 for(j = 0; j < r; j++) {
840 scanf("%d", &maxclaim[i][j]);
841 }
842 }
843
844 printf("\nEnter allocated resource table:\n");
845 for (i = 0; i < p; i++) {
846 for(j = 0; j < r; j++) {
847 scanf("%d", &curr[i][j]);
848 }
849 }
850
851 printf("\nThe resource of instances: ");
852 for (i = 0; i < r; i++) {
853 printf("\t%d", maxres[i]);
854 }
855
856 printf("\nThe allocated resource table:\n");
857 for (i = 0; i < p; i++) {
858 for (j = 0; j < r; j++) {
859 printf("\t%d", curr[i][j]);
860 }
861
862 printf("\n");
863 }
864
865 printf("\nThe maximum resource table:\n");
866 for (i = 0; i < p; i++) {
867 for (j = 0; j < r; j++) {
868 printf("\t%d", maxclaim[i][j]);
869 }
870
871 printf("\n");
872 }
873
874 for (i = 0; i < p; i++) {
875 for (j = 0; j < r; j++) {
876 alloc[j] += curr[i][j];
877 }
878 }
879
880 printf("\nAllocated resources:");
881 for (i = 0; i < r; i++) {
882 printf("\t%d", alloc[i]);
883 }
884
885 for (i = 0; i < r; i++) {
886 avl[i] = maxres[i] - alloc[i];
887 }
888
889 printf("\nAvailable resources:");
890 for (i = 0; i < r; i++) {
891 printf("\t%d", avl[i]);
892 }
893 printf("\n");
894
895 //Main procedure goes below to check for unsafe state.
896 while (count != 0) {
897 safe = 0;
898 for (i = 0; i < p; i++) {
899 if (running[i]) {
900 exec = 1;
901 for (j = 0; j < r; j++) {
902 if (maxclaim[i][j] - curr[i][j] > avl[j]) {
903 exec = 0;
904 break;
905 }
906 }
907 if (exec) {
908 printf("\nProcess%d is executing\n", i + 1);
909 running[i] = 0;
910 count--;
911 safe = 1;
912
913 for (j = 0; j < r; j++) {
914 avl[j] += curr[i][j];
915 }
916
917 break;
918 }
919 }
920 }
921 if (!safe) {
922 printf("\nThe processes are in unsafe state.\n");
923 break;
924 } else {
925 printf("\nThe process is in safe state");
926 printf("\nSafe sequence is:");
927
928 for (i = 0; i < r; i++) {
929 printf("\t%d", avl[i]);
930 }
931
932 printf("\n");
933 }
934 }
935}
936
937OR
938
939#include<stdio.h>
940 #include<conio.h>
941
942void main()
943{
944 int process,resource,i,j,instanc,k=0,count1=0,count2=0; //count,k variables are taken for counting purpose
945 printf("\n\t Enter No. of Process:-\n");
946 printf("\t\t");
947 scanf("%d",&process); //Entering No. of Processes
948 printf("\n\tEnter No. of Resources:-\n");
949 printf("\t\t");
950 scanf("%d",&resource); //No. of Resources
951
952 int avail[resource],max[process][resource],allot[process][resource],need[process][resource],completed[process];
953
954 for(i=0;i<process;i++)
955 completed[i]=0; //Setting Flag for uncompleted Process
956
957 printf("\n\tEnter No. of Available Instances\n");
958
959 for(i=0;i<resource;i++)
960 {
961 printf("\t\t");
962 scanf("%d",&instanc);
963 avail[i]=instanc; // Storing Available instances
964 }
965
966 printf("\n\tEnter Maximum No. of instances of resources that a Process need:\n");
967
968 for(i=0;i<process;i++)
969 {
970 printf("\n\t For P[%d]",i);
971 for(j=0;j<resource;j++)
972 {
973 printf("\t");
974 scanf("%d",&instanc);
975 max[i][j]=instanc;
976 }
977 }
978 printf("\n\t Enter no. of instances already allocated to process of a resource:\n");
979
980 for(i=0;i<process;i++)
981 {
982 printf("\n\t For P[%d]\t",i);
983 for(j=0;j<resource;j++)
984 {
985 printf("\t\t");
986 scanf("%d",&instanc);
987 allot[i][j]=instanc;
988 need[i][j]=max[i][j]-allot[i][j]; //calculating Need of each process
989 }
990 }
991printf("\n\t Safe Sequence is:- \t");
992
993 while(count1!=process)
994 {
995 count2=count1;
996 for(i=0;i<process;i++)
997 {
998 for(j=0;j<resource;j++)
999 {
1000 if(need[i][j]<=avail[j])
1001 {
1002 k++;
1003 }
1004 }
1005 if(k==resource && completed[i]==0 )
1006 {
1007 printf("P[%d]\t",i);
1008 completed[i]=1;
1009 for(j=0;j<resource;j++)
1010 {
1011 avail[j]=avail[j]+allot[i][j];
1012 }
1013 count1++;
1014 }
1015 k=0;
1016 }
1017
1018 if(count1==count2)
1019 {
1020 printf("\t\t Stop ..After this.....Deadlock \n");
1021 break;
1022 }
1023 }
1024 getch();
1025}
1026
1027
1028
1029READER WRITER PROBLEM
1030// STATE VARIABLES
1031// Number of active readers; initially = 0
1032int NReaders = 0;
1033
1034// Number of waiting readers; initially = 0
1035int WaitingReaders = 0;
1036
1037// Number of active writers; initially = 0
1038int NWriters = 0;
1039
1040// Number of waiting writers; initially = 0
1041int WaitingWriters = 0;
1042
1043Condition canRead = NULL;
1044Condition canWrite = NULL;
1045
1046Void BeginWrite()
1047{
1048
1049 // A writer can enter if there are no other
1050 // active writers and no readers are waiting
1051 if (NWriters == 1 || NReaders > 0) {
1052
1053 ++WaitingWriters;
1054 wait(CanWrite);
1055 --WaitingWriters;
1056 }
1057
1058 NWriters = 1;
1059}
1060
1061Void EndWrite()
1062{
1063
1064 NWriters = 0;
1065
1066 // Checks to see if any readers are waiting
1067 if (WaitingReaders)
1068
1069 Signal(CanRead);
1070
1071 else
1072
1073 Signal(CanWrite);
1074}
1075
1076Void BeginRead()
1077{
1078
1079 // A reader can enter if there are no writers
1080 // active or waiting, so we can have
1081 // many readers active all at once
1082 if (NWriters == 1 || WaitingWriters > 0) {
1083
1084 ++WaitingReaders;
1085
1086 // Otherwise, a reader waits (maybe many do)
1087 Wait(CanRead);
1088
1089 --WaitingReaders;
1090 }
1091
1092 ++NReaders;
1093 Signal(CanRead);
1094}
1095
1096Void EndRead()
1097{
1098
1099 // When a reader finishes, if it was the last reader,
1100 // it lets a writer in (if any is there).
1101 if (--NReaders == 0)
1102
1103 Signal(CanWrite);
1104}
1105
1106Readers-Writers Problem
1107
1108METHOD 1:
1109USING SEMAPHORES BUT USING PTREADS.H
1110#include<stdio.h>
1111#include<conio.h>
1112#include<stdbool.h>
1113struct semaphore
1114{
1115int mutex;
1116int rcount;
1117int rwait;
1118bool wrt;
1119};
1120voidaddR(struct semaphore *s)
1121{
1122if (s->mutex == 0 && s->rcount == 0)
1123{
1124printf("\nSorry, File open in Write mode.\nNew Reader added to queue.\n");
1125s->rwait++;
1126}
1127else
1128{
1129printf("\nReader Process added.\n");
1130s->rcount++;
1131s->mutex--;
1132}
1133return ;
1134}
1135voidaddW(struct semaphore *s)
1136{
1137if(s->mutex==1)
1138{
1139s->mutex--;
1140s->wrt=1;
1141printf("\nWriter Process added.\n");
1142}
1143else if(s->wrt) printf("\nSorry, Writer already operational.\n");
1144elseprintf("\nSorry, File open in Read mode.\n");
1145return ;
1146}
1147voidremR(struct semaphore *s)
1148{
1149if(s->rcount == 0) printf("\nNo readers to remove.\n");
1150else
1151{
1152printf("\nReader Removed.\n");
1153s->rcount--;
1154s->mutex++;
1155}
1156return ;
1157}
1158voidremW(struct semaphore *s)
1159{
1160if(s->wrt==0) printf("\nNo Writer to Remove");
1161else
1162{
1163printf("\nWriter Removed\n");
1164s->mutex++;
1165s->wrt=0;
1166if(s->rwait!=0)
1167{
1168s->mutex-=s->rwait;
1169s->rcount=s->rwait;
1170s->rwait=0;
1171printf("%d waiting Readers Added.",s->rcount);
1172}
1173}
1174}
1175int main()
1176{
1177struct semaphore S1={1,0,0};
1178while(1)
1179{
1180system("cls");
1181printf("Options :-\n1.Add Reader.\n2.Add Writer.\n3.Remove Reader.\n4.Remove Writer.\n5.Exit.\n\n\tChoice : ");
1182intch;
1183scanf("%d",&ch);
1184switch(ch)
1185{
1186case 1: addR(&S1); break;
1187case 2: addW(&S1); break;
1188case 3: remR(&S1); break;
1189case 4: remW(&S1); break;
1190case 5: printf("\n\tGoodBye!"); getch(); return 0;
1191default: printf("\nInvalid Entry!"); continue;
1192}
1193printf("\n\n<<<<<< Current Status >>>>>>\n\n\tMutex\t\t:\t%d\n\tActive Readers\t:\t%d\n\tWaiting Readers\t:\t%d\n\tWriter Active\t:\t%s\n\n", S1.mutex, S1.rcount, S1.rwait, (S1.mutex==0 && S1.rcount==0) ? "YES" : "NO");
1194system("pause");
1195}
1196}
1197METHOD 2:
1198WITHOUT USING SEMAPHORES BUT USING PTREADSH
1199PROGRAM:
1200#include<pthread.h>
1201#include<unistd.h>
1202#include<stdio.h>
1203#include<stdlib.h>
1204pthread_mutex_tx,wsem;
1205pthread_ttid;
1206intreadcount;
1207voidintialize()
1208{
1209pthread_mutex_init(&x,NULL);
1210pthread_mutex_init(&wsem,NULL);
1211readcount=0;
1212}
1213void * reader (void * param)
1214{
1215intwaittime;
1216waittime = rand() % 5;
1217printf("\nReader is trying to enter");
1218pthread_mutex_lock(&x);
1219readcount++;
1220if(readcount==1)
1221pthread_mutex_lock(&wsem);
1222printf("\n%d Reader is inside ",readcount);
1223pthread_mutex_unlock(&x);
1224sleep(waittime);
1225pthread_mutex_lock(&x);
1226readcount--;
1227if(readcount==0)
1228pthread_mutex_unlock(&wsem);
1229pthread_mutex_unlock(&x);
1230printf("\nReader is Leaving");
1231}
1232void * writer (void * param)
1233{
1234intwaittime;
1235waittime=rand() % 3;
1236printf("\nWriter is trying to enter");
1237pthread_mutex_lock(&wsem);
1238printf("\nWrite has entered");
1239sleep(waittime);
1240pthread_mutex_unlock(&wsem);
1241printf("\nWriter is leaving");
1242sleep(30);
1243exit(0);
1244}
1245int main()
1246{
1247int n1,n2,i;
1248printf("\nEnter the no of readers: ");
1249scanf("%d",&n1);
1250printf("\nEnter the no of writers: ");
1251scanf("%d",&n2);
1252for(i=0;i<n1;i++)
1253pthread_create(&tid,NULL,reader,NULL);
1254for(i=0;i<n2;i++)
1255pthread_create(&tid,NULL,writer,NULL);
1256sleep(30);
1257exit(0);
1258}
1259
1260
1261
1262
1263
1264
1265
1266DINING PHILOSIPHER
1267#include <pthread.h>
1268#include <semaphore.h>
1269#include <stdio.h>
1270
1271#define N 5
1272#define THINKING 2
1273#define HUNGRY 1
1274#define EATING 0
1275#define LEFT (phnum + 4) % N
1276#define RIGHT (phnum + 1) % N
1277
1278int state[N];
1279int phil[N] = { 0, 1, 2, 3, 4 };
1280
1281sem_t mutex;
1282sem_t S[N];
1283
1284void test(int phnum)
1285{
1286 if (state[phnum] == HUNGRY
1287 && state[LEFT] != EATING
1288 && state[RIGHT] != EATING) {
1289 // state that eating
1290 state[phnum] = EATING;
1291
1292 sleep(2);
1293
1294 printf("Philosopher %d takes fork %d and %d\n",
1295 phnum + 1, LEFT + 1, phnum + 1);
1296
1297 printf("Philosopher %d is Eating\n", phnum + 1);
1298
1299 // sem_post(&S[phnum]) has no effect
1300 // during takefork
1301 // used to wake up hungry philosophers
1302 // during putfork
1303 sem_post(&S[phnum]);
1304 }
1305}
1306
1307// take up chopsticks
1308void take_fork(int phnum)
1309{
1310
1311 sem_wait(&mutex);
1312
1313 // state that hungry
1314 state[phnum] = HUNGRY;
1315
1316 printf("Philosopher %d is Hungry\n", phnum + 1);
1317
1318 // eat if neighbours are not eating
1319 test(phnum);
1320
1321 sem_post(&mutex);
1322
1323 // if unable to eat wait to be signalled
1324 sem_wait(&S[phnum]);
1325
1326 sleep(1);
1327}
1328
1329// put down chopsticks
1330void put_fork(int phnum)
1331{
1332
1333 sem_wait(&mutex);
1334
1335 // state that thinking
1336 state[phnum] = THINKING;
1337
1338 printf("Philosopher %d putting fork %d and %d down\n",
1339 phnum + 1, LEFT + 1, phnum + 1);
1340 printf("Philosopher %d is thinking\n", phnum + 1);
1341
1342 test(LEFT);
1343 test(RIGHT);
1344
1345 sem_post(&mutex);
1346}
1347
1348void* philospher(void* num)
1349{
1350
1351 while (1) {
1352
1353 int* i = num;
1354
1355 sleep(1);
1356
1357 take_fork(*i);
1358
1359 sleep(0);
1360
1361 put_fork(*i);
1362 }
1363}
1364
1365int main()
1366{
1367
1368 int i;
1369 pthread_t thread_id[N];
1370
1371 // initialize the semaphores
1372 sem_init(&mutex, 0, 1);
1373
1374 for (i = 0; i < N; i++)
1375
1376 sem_init(&S[i], 0, 0);
1377
1378 for (i = 0; i < N; i++) {
1379
1380 // create philosopher processes
1381 pthread_create(&thread_id[i], NULL,
1382 philospher, &phil[i]);
1383
1384 printf("Philosopher %d is thinking\n", i + 1);
1385 }
1386
1387 for (i = 0; i < N; i++)
1388
1389 pthread_join(thread_id[i], NULL);
1390}
1391
1392
1393SHELL SCRIPTING
1394
1395$ cat > first
1396#
1397# My first shell script
1398#
1399clear
1400echo "Knowledge is Power"
1401Press Ctrl + D to save. Now our script is ready. To execute it type command
1402$ ./first
1403This will give error since we have not set Execute permission for our script first; to do this type
1404command
1405$ chmod +x first
1406$ ./first
1407First screen will be clear, then Knowledge is Power is printed on screen. To print message of
1408variables contains we user echo command, general form of echo command is as follows
1409echo "Message"
1410echo "Message variable1, variable2....variableN"
1411
1412
1413
1414
1415
1416
1417$ cat > demo
1418#!/bin/sh
1419#
1420# Script that demos, command line args
1421#
1422echo "Total number of command line argument are $#"
1423echo "$0 is script name"
1424echo "$1 is first argument"
1425echo $2 is second argument"
1426echo "All of them are :- $*"
1427Save the above script by pressing ctrl+d, now make it executable
1428$ chmod +x demo
1429$ ./demo Hello World
1430$ cp demo ~/bin
1431
1432$ demo
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443$ cat foo
1444$ echo $?
1445The cat command return zero(0) on successful, this can be used in if condition as follows, Write shell
1446script as
1447$ cat > showfile
1448#!/bin/sh
1449#
1450#Script to print file
1451#
1452if cat $1
1453then
1454echo -e "\n\nFile $1, found and successfully echoed"
1455fi
1456Now run it.
1457$ chmod +x showfile
1458$ ./showfile
1459
1460
1461
1462$ cat > ispostive
1463#!/bin/sh
1464#
1465# Script to see whether argument is positive
1466#
1467if test $1 -gt 0
1468then
1469echo "$1 number is positive"
1470fi
1471Run it as follows
1472$ chmod +x ispostive
1473$ ispostive 5
1474Here o/p : 5 number is positive
1475$ispostive -45
1476Here o/p : Nothing is printed
1477$ispostive
1478Here o/p : ./ispostive: test: -gt: unary operator expected
1479
1480
1481# Script to see whether argument is positive or negative
1482#
1483if [ $# -eq 0 ]
1484then
1485echo "$0 : You must give/supply one integers"
1486exit 1
1487fi
1488if test $1 -gt 0
1489then
1490echo "$1 number is positive"
1491else
1492echo "$1 number is negative"
1493fi
1494
1495
1496$ cat > testfor
1497for i in 1 2 3 4 5
1498do
1499echo "Welcome $i times"
1500done
1501Run it as,
1502$ chmod +x testfor
1503$ ./testfor
1504
1505
1506Linux Shell Script Tutorial
1507$ cat > mtable
1508#!/bin/sh
1509#
1510#Script to test for loop
1511if [ $# -eq 0 ]
1512then
1513echo "Error - Number missing form command line argument"
1514echo "Syntax : $0 number"
1515echo " Use to print multiplication table for given number"
1516exit 1
1517fi
1518n=$1
1519for i in 1 2 3 4 5 6 7 8 9 10
1520do
1521echo "$n * $i = `expr $i \* $n`"
1522done
1523Save and Run it as
1524$ chmod +x mtable
1525$ ./mtable 7
1526$ ./mtable