-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalldsquestion.txt
2040 lines (2040 loc) · 65.6 KB
/
alldsquestion.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
OS LAB QUESTIONS
1. Write a shell script to sort an array of numbers using any sort method.
#!/bin/bash
echo "enter maximum number"
read n
# taking input from user
echo "enter Numbers in array:"
for (( i = 0; i < $n; i++ ))
do
read nos[$i]
done
#printing the number before sorting
echo "Numbers in an array are:"
for (( i = 0; i < $n; i++ ))
do
echo ${nos[$i]}
done
# Now do the Sorting of numbers
for (( i = 0; i < $n ; i++ ))
do
for (( j = $i; j < $n; j++ ))
do
if [ ${nos[$i]} -gt ${nos[$j]} ]; then
t=${nos[$i]}
nos[$i]=${nos[$j]}
nos[$j]=$t
fi
done
done
# Printing the sorted number
echo -e "\nSorted Numbers "
for (( i=0; i < $n; i++ ))
do
echo ${nos[$i]}
done
2. Write down Linux commands for following statements:
i. Redirect the output of ls command to a file named outfile. Use this as an input
file for remaining commands.
Command:
ls > outfile
wc -l < outfile
cat outfile
This will write the output of ls to a file called outfile in the current working directory.
You can then use the outfile file as an input file for remaining commands. For example, if
you want to count the number of lines in outfile, you can use the following command:
ii. To select the lines in a file which has digit as one of the character in that line
and redirect the output to the file named list.
You can use the grep command to select the lines in a file that have a digit as one
of the characters. You can then redirect the output to a file named list using the >
operator. Here is the command:
Command:
grep '[0-9]' <input_file> > list
cat list
Replace <input_file> with the name of the file that you want to search for lines with digits.
In this command, the regular expression [0-9] matches any line that contains a digit from
0 to 9. The < operator is used to redirect the input from the file to the grep command.
The > operator is used to redirect the output of the grep command to the list file.
After running this command, the list file will contain all the lines from the input file that
have at least one digit.
iii. Assign execute permission to owner and remove read permission from other
for an ordinary file named test by relative way.
You can use the chmod command to assign execute permission to the owner and
remove read permission from others for an ordinary file named test. Here is the
command:
Command:chmod u+x,o-r <path_to_file>/test
(pwd to check path to file)
ls -la
Replace <path_to_file> with the path to the directory containing the test file. For example, if
the file is in the current working directory, you can replace <path_to_file> with . (a dot,
representing the current directory).
In this command, u+x assigns execute permission to the owner of the file, and o-r
removes read permission from others. The + and - symbols are used to add or remove
permissions, respectively. The u and o are short for "user" and "others", respectively.
After running this command, the owner of the test file will have execute permission, and
others will not have read permission.
iv. Create an alias named rm that always deletes file interactively.
You can create an alias named rm that always deletes files interactively by adding the
following line to your shell configuration file:
Command:
alias rm='rm -i'
rm
(-i is used for confirmation)
This will add an alias to the rm command that always prompts for confirmation before
deleting files.
v. Count the currently login users to the system.
Command: who | wc -l
3. Write down Linux commands for following statements:
i. Redirect the output of cat command to a file named outfile. Use this as an input
file for remaining commands.
i. To redirect the output of cat command to a file named outfile and use it as an input file for
remaining commands, use the following command:
Command : cat inputfile.txt > outfile
This will output the contents of inputfile.txt to outfile, replacing any previous content in outfile.
You can then use the outfile as the input file for remaining commands.
ii. List all hidden files under current directory and store in “hidden” file
ii. To list all hidden files under the current directory and store in a file named "hidden", use the
following command:
Command : ls -a | grep "^\." > hidden
This command first lists all files in the current directory, including hidden files, using the ls
command with the -a option. The output is then piped to the grep command, which searches for
lines that begin with a period (which indicates a hidden file in Linux). The output of grep is then
redirected to a file named "hidden".
iii. Assign write permission to owner and remove execute permission from other
for an ordinary file named test by absolute way.
iii. To assign write permission to the owner and remove execute permission from others for an
ordinary file named "test" using the absolute method, use the following command:
Commands : chmod 640 /path/to/test
This command sets the file permissions to 640, which means that the owner has read and write
permissions, the group has read permission, and others have no permissions. This removes
execute permission from others, while still allowing the owner to execute the file if it is
executable.
iv. To create soft and hard link for given file
iv. To create a soft and hard link for a given file, use the following commands:
For Soft Link:
Command: ln -s /path/to/original_file /path/to/soft_link
For a hard link:
Command : ln /path/to/original_file /path/to/hard_link
In both cases, replace "/path/to/original_file" with the path to the original file, and "/path/to/link"
with the path to the link you want to create.
v. To convert lowercase to upper case of a given file
To convert lowercase to uppercase of a given file, use the following command:
Command : tr '[:lower:]' '[:upper:]' < inputfile.txt > outfile
This command uses the tr command to convert all lowercase characters in inputfile.txt to
uppercase, and then redirects the output to a file named "outfile".
vi. To extract 1st and 10th character of a given file
vi. To extract the 1st and 10th character of a given file, use the following command:
Command : cut -c 1,10 inputfile.txt
This command uses the cut command to extract the 1st and 10th character of each line in
inputfile.txt. The "-c" option tells cut to extract characters, and "1,10" specifies the character
positions to extract.
vii. To display how many times lines are repeated in a given file
To display how many times lines are repeated in a given file, you can use the uniq
command with the sort and uniq options.
command:sort <file_name> | uniq -c
Replace <file_name> with the name of the file you want to analyze.
In this command, the sort command is used to sort the contents of the file
alphabetically. Then, the output is piped to the uniq command with the -c option, which
counts the number of occurrences of each unique line. The output will display the count
followed by the unique line, like this:
4. Write a program to solve reader-writer problem using Mutex
The reader-writer problem is a classic synchronization problem in computer science where
multiple threads (or processes) access a shared resource. In this problem, readers can read the
shared resource concurrently, but writers must have exclusive access to it to write. Here is a C
program that uses a mutex to solve the reader-writer problem:
Code :
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
/*
This program provides a possible solution for first readers writers problem using mutex and
semaphore.
I have used 10 readers and 5 producers to demonstrate the solution. You can always play with
these values.
*/
sem_t wrt;
pthread_mutex_t mutex;
int cnt = 1;
int numreader = 0;
void *writer(void *wno)
{
sem_wait(&wrt);
cnt = cnt*2;
printf("Writer %d modified cnt to %d\n",(*((int *)wno)),cnt);
sem_post(&wrt);
}
void *reader(void *rno)
{
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);
numreader++;
if(numreader == 1) {
sem_wait(&wrt); // If this id the first reader, then it will block the writer
}
pthread_mutex_unlock(&mutex);
// Reading Section
printf("Reader %d: read cnt as %d\n",*((int *)rno),cnt);
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);
numreader--;
if(numreader == 0) {
sem_post(&wrt); // If this is the last reader, it will wake up the writer.
}
pthread_mutex_unlock(&mutex);
}
int main()
{
pthread_t read[10],write[5];
pthread_mutex_init(&mutex, NULL);
sem_init(&wrt,0,1);
int a[10] = {1,2,3,4,5,6,7,8,9,10}; //Just used for numbering the producer and consumer
for(int i = 0; i < 10; i++) {
pthread_create(&read[i], NULL, (void *)reader, (void *)&a[i]);
}
for(int i = 0; i < 5; i++) {
pthread_create(&write[i], NULL, (void *)writer, (void *)&a[i]);
}
for(int i = 0; i < 10; i++) {
pthread_join(read[i], NULL);
}
for(int i = 0; i < 5; i++) {
pthread_join(write[i], NULL);
}
pthread_mutex_destroy(&mutex);
sem_destroy(&wrt);
return 0;
}
The above code is a solution to the first readers-writers problem using mutex and semaphore in
the C programming language.
The program uses 10 reader threads and 5 writer threads to demonstrate the solution, which
can be changed by modifying the values in the main function.
The program starts by including the necessary libraries: pthread.h for threads, semaphores.h for
semaphores, and stdio.h for standard input and output.
The global variables used in the program are:
● wrt: a semaphore to ensure that only one writer accesses the shared resource at a time.
● mutex: a mutex to protect the numreader variable.
● cnt: a counter variable that is shared between the reader and writer threads.
● numreader: a variable that keeps track of the number of readers accessing the shared
resource.
The program then defines two functions, writer and reader, that will be called by the respective
threads.
5. Write a program to solve producer-consumer problem using semaphore
Code :
// C program for the above approach
#include <stdio.h>
#include <stdlib.h>
// Initialize a mutex to 1
int mutex = 1;
// Number of full slots as 0
int full = 0;
// Number of empty slots as size
// of buffer
int empty = 10, x = 0;
// Function to produce an item and
// add it to the buffer
void producer()
{
// Decrease mutex value by 1
--mutex;
// Increase the number of full
// slots by 1
++full;
// Decrease the number of empty
// slots by 1
--empty;
// Item produced
x++;
printf("\nProducer produces"
"item %d",
x);
// Increase mutex value by 1
++mutex;
}
// Function to consume an item and
// remove it from buffer
void consumer()
{
// Decrease mutex value by 1
--mutex;
// Decrease the number of full
// slots by 1
--full;
// Increase the number of empty
// slots by 1
++empty;
printf("\nConsumer consumes "
"item %d",
x);
x--;
// Increase mutex value by 1
++mutex;
}
// Driver Code
int main()
{
int n, i;
printf("\n1. Press 1 for Producer"
"\n2. Press 2 for Consumer"
"\n3. Press 3 for Exit");
// Using '#pragma omp parallel for'
// can give wrong value due to
// synchronization issues.
// 'critical' specifies that code is
// executed by only one thread at a
// time i.e., only one thread enters
// the critical section at a given time
#pragma omp critical
for (i = 1; i > 0; i++) {
printf("\nEnter your choice:");
scanf("%d", &n);
// Switch Cases
switch (n) {
case 1:
// If mutex is 1 and empty
// is non-zero, then it is
// possible to produce
if ((mutex == 1)
&& (empty != 0)) {
producer();
}
// Otherwise, print buffer
// is full
else {
printf("Buffer is full!");
}
break;
case 2:
// If mutex is 1 and full
// is non-zero, then it is
// possible to consume
if ((mutex == 1)
&& (full != 0)) {
consumer();
}
// Otherwise, print Buffer
// is empty
else {
printf("Buffer is empty!");
}
break;
// Exit Condition
case 3:
exit(0);
break;
}
}
}
Explanation :
The producer is to either go to sleep or discard data if the buffer is full. The next time the
consumer removes an item from the buffer, it notifies the producer, who starts to fill the
buffer again. In the same manner, the consumer can go to sleep if it finds the buffer to be
empty. The next time the producer puts data into the buffer, it wakes up the sleeping
consumer.
6. Write a program to solve dining philosopher problem using semaphore
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;
public class dining_philosopher {
static int philosopher = 5;
static Philosopher philosophers[] = new Philosopher[philosopher];
static Chopstick chopsticks[] = new Chopstick[philosopher];
static class Chopstick {
public Semaphore mutex = new Semaphore(1);
void grab() {
try {
mutex.acquire();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
void release() {
mutex.release();
}
boolean isFree() {
return mutex.availablePermits() > 0;
}
}
static class Philosopher extends Thread {
public int number;
public Chopstick leftchopstick;
public Chopstick rightchopstick;
Philosopher(int num, Chopstick left, Chopstick right) {
number = num;
leftchopstick = left;
rightchopstick = right;
}
public void run() {
while (true) {
leftchopstick.grab();
System.out.println("Philosopher " + (number + 1) + " grabs left chopstick.");
rightchopstick.grab();
System.out.println("Philosopher " + (number + 1) + " grabs right chopstick.");
eat();
leftchopstick.release();
System.out.println("Philosopher " + (number + 1) + " releases left chopstick.");
rightchopstick.release();
System.out.println("Philosopher " + (number + 1) + " releases right
chopstick.");
}
}
void eat() {
try {
int sleepTime = ThreadLocalRandom.current().nextInt(0, 1000);
System.out.println("Philosopher " + (number + 1) + " eats for " + sleepTime +
"ms");
Thread.sleep(sleepTime);
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
public static void main(String args[]) {
for (int i = 0; i < philosopher; i++) {
chopsticks[i] = new Chopstick();
}
for (int i = 0; i < philosopher; i++) {
philosophers[i] = new Philosopher(i, chopsticks[i], chopsticks[(i + 1) %
philosopher]);
philosophers[i].start();
}
while (true) {
try {
Thread.sleep(1000);
boolean deadlock = true;
for (Chopstick cs : chopsticks) {
if (cs.isFree()) {
deadlock = false;
break;
}
}
if (deadlock) {
Thread.sleep(1000);
System.out.println("Everyone Eats");
break;
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
System.out.println("Exit The Program!");
System.exit(0);
}
}
7. Draw the Gantt charts and compute the finish time, turnaround time and waiting
time for the following algorithms:
A. First come First serve
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int process_id;
int arrival_time;
int burst_time;
int finish_time;
int turnaround_time;
int waiting_time;
} Process;
void compute_metrics(Process* processes, int num_processes) {
int total_time = 0;
for (int i = 0; i < num_processes; i++) {
if (total_time < processes[i].arrival_time) {
total_time = processes[i].arrival_time;
}
total_time += processes[i].burst_time;
processes[i].finish_time = total_time;
processes[i].turnaround_time = processes[i].finish_time - processes[i].arrival_time;
processes[i].waiting_time = processes[i].turnaround_time - processes[i].burst_time;
}
}
void print_gantt_chart(Process* processes, int num_processes) {
int total_time = processes[num_processes - 1].finish_time;
int* remaining_time = (int*)malloc(num_processes * sizeof(int));
for (int i = 0; i < num_processes; i++) {
remaining_time[i] = processes[i].burst_time;
}
printf("\nGantt Chart:\n");
printf("------------\n");
printf("|");
int current_time = 0;
while (current_time < total_time) {
int next_process_id = -1;
for (int i = 0; i < num_processes; i++) {
if (remaining_time[i] > 0 && processes[i].arrival_time <= current_time) {
if (next_process_id == -1 || remaining_time[i] <
remaining_time[next_process_id]) {
next_process_id = i;
}
}
}
if (next_process_id == -1) {
current_time++;
printf(" ");
} else {
printf("P%d", processes[next_process_id].process_id);
remaining_time[next_process_id]--;
current_time++;
}
printf("|");
}
printf("\n");
free(remaining_time);
}
int main() {
int num_processes;
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
Process* processes = (Process*)malloc(num_processes * sizeof(Process));
printf("\nEnter the arrival time and burst time for each process:\n");
for (int i = 0; i < num_processes; i++) {
printf("Process %d:\n", i + 1);
printf("Arrival time: ");
scanf("%d", &processes[i].arrival_time);
printf("Burst time: ");
scanf("%d", &processes[i].burst_time);
processes[i].process_id = i + 1;
}
compute_metrics(processes, num_processes);
printf("\nProcess Arrival time Burst time Finish time Turnaround time Waiting
time\n");
for (int i = 0; i < num_processes; i++) {
printf("%-9d%-15d%-13d%-15d%-18d%d\n", processes[i].process_id,
processes[i].arrival_time, processes[i].burst_time, processes[i].finish_time,
processes[i].turnaround_time, processes[i].waiting_time);
}
print_gantt_chart(processes, num_processes);
free(processes);
return 0;
}
B. Shortest Job First (Non Preemptive)
#include<stdio.h>
#include<stdlib.h>
struct Process {
int pid; // process id
int arrival_time; // arrival time
int burst_time; // burst time
int finish_time; // finish time
int turnaround_time; // turnaround time
int waiting_time; // waiting time
};
void swap(struct Process* a, struct Process* b) {
struct Process temp = *a;
*a = *b;
*b = temp;
}
void sort_processes_by_burst_time(struct Process* processes, int num_processes) {
for (int i = 0; i < num_processes - 1; i++) {
for (int j = i + 1; j < num_processes; j++) {
if (processes[i].burst_time > processes[j].burst_time) {
swap(&processes[i], &processes[j]);
}
}
}
}
void compute_metrics(struct Process* processes, int num_processes) {
processes[0].finish_time = processes[0].burst_time + processes[0].arrival_time;
processes[0].turnaround_time = processes[0].finish_time - processes[0].arrival_time;
processes[0].waiting_time = 0;
for (int i = 1; i < num_processes; i++) {
processes[i].finish_time = processes[i-1].finish_time + processes[i].burst_time;
processes[i].turnaround_time = processes[i].finish_time - processes[i].arrival_time;
processes[i].waiting_time = processes[i].turnaround_time - processes[i].burst_time;
}
}
void print_gantt_chart(struct Process* processes, int num_processes) {
printf("\nGantt Chart:\n");
printf("-----------\n");
for (int i = 0; i < num_processes; i++) {
printf("| P%d ", processes[i].pid);
}
printf("|\n");
printf("0");
for (int i = 0; i < num_processes; i++) {
printf(" %d", processes[i].finish_time);
}
printf("\n");
}
int main() {
int num_processes;
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
struct Process* processes = (struct Process*) malloc(num_processes * sizeof(struct
Process));
printf("\nEnter the arrival time and burst time for each process:\n");
for (int i = 0; i < num_processes; i++) {
processes[i].pid = i + 1;
printf("Process %d:\n", processes[i].pid);
printf("Arrival time: ");
scanf("%d", &processes[i].arrival_time);
printf("Burst time: ");
scanf("%d", &processes[i].burst_time);
}
sort_processes_by_burst_time(processes, num_processes);
compute_metrics(processes, num_processes);
printf("\nProcess\t Arrival time\t Burst time\t Finish time\t Turnaround time\t Waiting
time\n");
for (int i = 0; i < num_processes; i++) {
printf("%d\t %d\t\t %d\t\t %d\t\t %d\t\t\t %d\n",
processes[i].pid, processes[i].arrival_time, processes[i].burst_time,
processes[i].finish_time,
processes[i].turnaround_time, processes[i.waiting_time);
}
print_gantt_chart(processes, num_processes);
free(processes);
return 0;
}
8. Draw the Gantt charts and compute the finish time, turnaround time and waiting
time for the following algorithms:
A. First come First serve
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int process_id;
int arrival_time;
int burst_time;
int finish_time;
int turnaround_time;
int waiting_time;
} Process;
void compute_metrics(Process* processes, int num_processes) {
int total_time = 0;
for (int i = 0; i < num_processes; i++) {
if (total_time < processes[i].arrival_time) {
total_time = processes[i].arrival_time;
}
total_time += processes[i].burst_time;
processes[i].finish_time = total_time;
processes[i].turnaround_time = processes[i].finish_time - processes[i].arrival_time;
processes[i].waiting_time = processes[i].turnaround_time - processes[i].burst_time;
}
}
void print_gantt_chart(Process* processes, int num_processes) {
int total_time = processes[num_processes - 1].finish_time;
int* remaining_time = (int*)malloc(num_processes * sizeof(int));
for (int i = 0; i < num_processes; i++) {
remaining_time[i] = processes[i].burst_time;
}
printf("\nGantt Chart:\n");
printf("------------\n");
printf("|");
int current_time = 0;
while (current_time < total_time) {
int next_process_id = -1;
for (int i = 0; i < num_processes; i++) {
if (remaining_time[i] > 0 && processes[i].arrival_time <= current_time) {
if (next_process_id == -1 || remaining_time[i] <
remaining_time[next_process_id]) {
next_process_id = i;
}
}
}
if (next_process_id == -1) {
current_time++;
printf(" ");
} else {
printf("P%d", processes[next_process_id].process_id);
remaining_time[next_process_id]--;
current_time++;
}
printf("|");
}
printf("\n");
free(remaining_time);
}
int main() {
int num_processes;
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
Process* processes = (Process*)malloc(num_processes * sizeof(Process));
printf("\nEnter the arrival time and burst time for each process:\n");
for (int i = 0; i < num_processes; i++) {
printf("Process %d:\n", i + 1);
printf("Arrival time: ");
scanf("%d", &processes[i].arrival_time);
printf("Burst time: ");
scanf("%d", &processes[i].burst_time);
processes[i].process_id = i + 1;
}
compute_metrics(processes, num_processes);
printf("\nProcess Arrival time Burst time Finish time Turnaround time Waiting
time\n");
for (int i = 0; i < num_processes; i++) {
printf("%-9d%-15d%-13d%-15d%-18d%d\n", processes[i].process_id,
processes[i].arrival_time, processes[i].burst_time, processes[i].finish_time,
processes[i].turnaround_time, processes[i].waiting_time);
}
print_gantt_chart(processes, num_processes);
free(processes);
return 0;
}
B. Round- Robin
9. Draw the Gantt charts and compute the finish time, turnaround time and waiting
time for the following algorithms:
A. First come First serve
B. Priority scheduling (Non Preemptive)
Assuming we have the following process information:
Process Arrival Time Burst Time Priority
P1 0 5 2
P2 1 3 1
P3 2 1 3
P4 3 2 4
P5 4 4 5
A. First Come First Serve (FCFS) Scheduling Algorithm:
Gantt Chart:
| P1 | P2 | P3 | P4 | P5 |
0 5 8 9 11 15
Calculation of finish time, turnaround time, and waiting time:
Process | Arrival Time | Burst Time | Finish Time | Turnaround Time | Waiting Time
P1 | 0 | 5 | 5 | 5 | 0
P2 | 1 | 3 | 8 | 7 | 4
P3 | 2 | 1 | 9 | 7 | 6
P4 | 3 | 2 | 11 | 8 | 6
P5 | 4 | 4 | 15 | 11 | 7
B. Priority Scheduling (Non-preemptive) Algorithm:
Gantt Chart:
| P2 | P1 | P3 | P4 | P5 |
1 6 7 9 13 17
Calculation of finish time, turnaround time, and waiting time:
Process | Arrival Time | Burst Time | Priority | Finish Time | Turnaround Time | Waiting Time
P2 | 1 | 3 | 1 | 4 | 3 | 0
P1 | 0 | 5 | 2 | 9 | 9 | 4
P3 | 2 | 1 | 3 | 8 | 6 | 5
P4 | 3 | 2 | 4 | 11 | 8 | 6
P5 | 4 | 4 | 5 | 17 | 13 | 9
Note: Turnaround time is the time difference between the completion time and arrival time of the
process, and waiting time is the time difference between the turnaround time and the burst time
of the process.
10. Write a Shell script to check whether given number is prime or not. Also print the
reverse of the given number.
Code:
#!/bin/bash
echo -n "Enter a number: "
read num
reverse=0
original=$num
while [ $num -gt 0 ]
do
remainder=$(( $num % 10 ))
reverse=$(( $reverse * 10 + $remainder ))
num=$(( $num / 10 ))
done
if [ $original -eq $reverse ]
then
echo "$original is a palindrome"
echo "Reverse of $original is $reverse"
else
echo "$original is not a palindrome"
echo "Reverse of $original is $reverse"
Fi
11. Write a program to solve reader-writer problem using semaphore
Code:
import java.util.concurrent.Semaphore;
class reader_writer {
static Semaphore readLock = new Semaphore(1);
static Semaphore writeLock = new Semaphore(1);
static int readCount = 0;
static class Read implements Runnable {
@Override
public void run() {
try {
readLock.acquire();
readCount++;
if (readCount == 1) {
writeLock.acquire();
}
readLock.release();
System.out.println(Thread.currentThread().getName() + " is READING");
Thread.sleep(1500);
System.out.println(Thread.currentThread().getName() + " has FINISHED READING");
readLock.acquire();
readCount--;
if (readCount == 0) {
writeLock.release();
}
readLock.release();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
static class Write implements Runnable {
@Override
public void run() {
try {
writeLock.acquire();
System.out.println(Thread.currentThread().getName() + " is WRITING");
Thread.sleep(2500);
System.out.println(Thread.currentThread().getName() + " has finished WRITING");
writeLock.release();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) throws Exception {
Read read = new Read();
Write write = new Write();
Thread t1 = new Thread(read);
t1.setName("Reader1");
Thread t2 = new Thread(read);
t2.setName("Reader2");
Thread t3 = new Thread(write);
t3.setName("Writer1");
Thread t4 = new Thread(read);
t4.setName("Reader3");
t1.start();
t3.start();
t2.start();
t4.start();
}
}
12. Write a program to solve producer-consumer problem using Mutex
Code:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConsumerMutex {
private static final int MAX_QUEUE_SIZE = 10;
private static final int NUM_PRODUCERS = 2;
private static final int NUM_CONSUMERS = 2;
private static Queue<Integer> buffer = new LinkedList<>();
private static Lock lock = new ReentrantLock();
public static void main(String[] args) {
Thread[] producerThreads = new Thread[NUM_PRODUCERS];
Thread[] consumerThreads = new Thread[NUM_CONSUMERS];
for (int i = 0; i < NUM_PRODUCERS; i++) {
producerThreads[i] = new Thread(new Producer());
producerThreads[i].start();
}
for (int i = 0; i < NUM_CONSUMERS; i++) {
consumerThreads[i] = new Thread(new Consumer());
consumerThreads[i].start();
}
for (int i = 0; i < NUM_PRODUCERS; i++) {
try {
producerThreads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < NUM_CONSUMERS; i++) {
try {
consumerThreads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Producer implements Runnable {
private Random random = new Random();
@Override
public void run() {
while (true) {
try {
lock.lock();
while (buffer.size() == MAX_QUEUE_SIZE) {
System.out.println("Buffer is full, waiting for consumer...");
lock.unlock();
Thread.sleep(1000);
lock.lock();
}
int item = random.nextInt(100);
buffer.add(item);
System.out.println("Produced item: " + item);
lock.unlock();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Consumer implements Runnable {
@Override
public void run() {
while (true) {
try {
lock.lock();
while (buffer.isEmpty()) {
System.out.println("Buffer is empty, waiting for producer...");
lock.unlock();
Thread.sleep(1000);
lock.lock();
}
int item = buffer.remove();
System.out.println("Consumed item: " + item);
lock.unlock();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
13. Write a shell script to check and count occurrence of a sub-string in the given
string using command line arguments.
#!/bin/bash
# Check that two arguments were provided
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <string> <substring>"
exit 1
fi
string="$1"
substring="$2"
# Use grep and wc commands to count the occurrence of the substring in the string
count=$(echo "$string" | grep -o "$substring" | wc -l)
echo "The substring '$substring' appears in the string '$string' $count times."
Command: ./substring_count.sh "Hello world" "l"
Or bash filename “Hello world” “l”
Here's how the script works:
● The if statement checks that two arguments were provided on the command line.
If not, it prints a usage message and exits with an error code.
● The first argument is assigned to the string variable, and the second argument is
assigned to the substring variable.
● The echo command pipes the string variable to the grep command with the -o
option, which outputs only the matching substrings. The output is then piped to
the wc command with the -l option, which counts the number of lines in the
output (i.e., the number of occurrences of the substring).
● The result is assigned to the count variable.
● The script prints a message that indicates how many times the substring
appears in the string.
To use the script, save it to a file (e.g., substring_count.sh), make it executable with chmod
+x substring_count.sh, and then run it with two arguments, like this:
14. Write a program to implement Banker’s algorithm.
#include <stdio.h>
#include <stdbool.h>
int main() {
int n, m; // n is the number of processes and m is the number of resources
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter the number of resources: ");
scanf("%d", &m);
int allocation[n][m], max[n][m], need[n][m], available[m], work[m], finish[n];
// Get the allocation matrix
printf("\nEnter the allocation matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &allocation[i][j]);
}
}
// Get the max matrix
printf("\nEnter the max matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &max[i][j]);
need[i][j] = max[i][j] - allocation[i][j];
}
finish[i] = 0;
}
// Get the available vector
printf("\nEnter the available vector:\n");
for (int i = 0; i < m; i++) {
scanf("%d", &available[i]);
work[i] = available[i];
}
// Run the algorithm
int count = 0;
bool found = true;
int safe_sequence[n], safe_count = 0;
while (count < n && found) {
found = false;
for (int i = 0; i < n; i++) {
if (!finish[i]) {
bool can_run = true;
for (int j = 0; j < m; j++) {
if (need[i][j] > work[j]) {
can_run = false;
break;
}
}
if (can_run) {
for (int j = 0; j < m; j++) {
work[j] += allocation[i][j];
}
safe_sequence[safe_count] = i;
safe_count++;
finish[i] = true;
count++;
found = true;
}
}
}
}
// Print the result
if (count == n) {
printf("\nThe system is in a safe state.\n");
printf("Safe sequence: ");
for (int i = 0; i < n; i++) {
printf("%d", safe_sequence[i]);
if (i != n - 1) {
printf(" -> ");
}
}
printf("\n");
} else {
printf("\nThe system is not in a safe state.\n");
}
return 0;
}
Explanation:
This program is an implementation of the Banker's algorithm for resource allocation in
operating systems. It takes user input for the number of processes and resources, as well
as allocation, max, and available matrices/vectors. It then runs the Banker's algorithm to
determine if the system is in a safe state, and if so, prints the safe sequence of
processes.
Here is a breakdown of the program:
1. First, the program prompts the user to enter the number of processes and
resources, and declares various arrays/matrices to store the input and
intermediate results.
2. Next, the program prompts the user to enter the allocation matrix, which
represents the number of resources currently allocated to each process.
3. The program then prompts the user to enter the max matrix, which represents the
maximum number of resources each process may need to complete its task.
4. The program calculates the need matrix, which represents the difference between
the max and allocation matrices for each process.
5. The program prompts the user to enter the available vector, which represents the
number of available resources of each type.
6. The program initializes the work vector to be a copy of the available vector, and
initializes the finish array to all 0's, since no processes have yet finished.
7. The program enters a loop, where it checks each process to see if it can be run
safely. It does this by checking if the need for each resource is less than or equal