OS Assignment 1 Solution
OS Assignment 1 Solution
Sangeeth Suresh
January 27, 2025
Student Details
• Class: S4 B2
• Roll Number: 68
Instructions
Develop a program in C to address the following scenario.
Questions
Question 1
There are 2 processes P1 and P2, both share an array of integers (shared memory). P1
accepts the array of integer and appends it to the shared array. Once P1 has appended
all the numbers into the array, P2 sorts the array in descending order. Once P2 finishes
sorting, P1 displays the sorted array in the terminal.
Answer:
1 # include < stdio .h >
2 # include < stdlib .h >
3 # include < unistd .h >
4 # include < sys / types .h >
5 # include < sys / wait .h >
6
1
19 }
20
21 int main () {
22 int array [ MAX_SIZE ];
23 int size ;
24
40 if ( pid < 0) {
41 perror ( " fork " ) ;
42 exit (1) ;
43 } else if ( pid == 0) {
44 // Child process : Sort the array
45 printf ( " Child process sorting ...\ n " ) ;
46 sort_descending ( array , size ) ;
47 printf ( " Sorting complete \ n " ) ;
48
2
69 }
70
83 return 0;
84 }
Question 2
Implement a message queue where the sender sends a message to receiver receives the
message ,reverses it and retransmit to the sender. Sender has to print the reversed
message. This process is continued till “exit” is send as the message.
Answer:
1 # include < stdio .h >
2 # include < stdlib .h >
3 # include < string .h >
4 # include < sys / types .h >
5 # include < sys / wait .h >
6 # include < unistd .h >
7 # include < fcntl .h >
8 # include < sys / stat .h >
9
3
28 }
29 fprintf ( flag_file , " % s " , flag ) ;
30 fclose ( flag_file ) ;
31 }
32
47 int main () {
48 pid_t pid = fork () ;
49
50 if ( pid < 0) {
51 perror ( " fork " ) ;
52 exit (1) ;
53 } else if ( pid == 0) {
54 // Child process ( Receiver )
55 char message [ MAX_TEXT ];
56
57 while (1) {
58 // Wait for the parent to signal the message is ready
59 wait_for_flag ( " parent_done " ) ;
60
4
78 file = fopen ( TEMP_FILE , " w " ) ;
79 if (! file ) {
80 perror ( " fopen " ) ;
81 exit (1) ;
82 }
83 fprintf ( file , " % s " , message ) ;
84 fclose ( file ) ;
85
90 exit (0) ;
91 } else {
92 // Parent process ( Sender )
93 char message [ MAX_TEXT ];
94
98 while (1) {
99 printf ( " Enter a message ( or ’ exit ’ to quit ) : " ) ;
100 fgets ( message , MAX_TEXT , stdin ) ;
101 message [ strcspn ( message , " \ n " ) ] = ’ \0 ’; // Remove
newline character
102
5
128 fgets ( message , MAX_TEXT , file ) ;
129 fclose ( file ) ;
130
141 return 0;
142 }