Os Viva
Os Viva
#include <stdio.h>
This preprocessor directive includes the standard input/output header file. It
allows the use of functions like printf().
#include <sys/types.h>
This header defines data types used in system calls, including pid_t for process
IDs.
#include <unistd.h>
This header provides access to the POSIX API, including functions like fork().
int main()
The main() function is the entry point of the program.
fork();
This is the critical system call in the program. The fork() function creates a new
process by duplicating the calling process. It returns:
printf("Hello world!\n");
This function prints "Hello world!" to the standard output (usually the terminal).
Since both the parent and child processes are running this statement, "Hello
world!" will be printed twice—once by the parent and once by the child.
However, because of the way process scheduling works, the exact order of the
printed messages is not guaranteed. You might see both messages back-to-back, or
there could be an interleaving of outputs if more statements are added.
return 0;
This terminates the main() function, returning a value of 0 to indicate successful
completion of the program.
In summary:
The fork() system call creates a new process.
Both the parent and child processes execute the printf() function, so "Hello
world!" is printed twice.
ORPHAN:
This C program demonstrates an orphan process—a child process that continues to run
even after its parent process terminates. Let's walk through it line by line:
1. #include<stdio.h>
This includes the Standard Input/Output library, which allows using functions like
printf() for output to the console.
2. #include<sys/types.h>
This header defines various types used in system calls, particularly pid_t, which
represents process IDs.
3. #include<unistd.h>
This header provides access to the POSIX API, including the fork() and sleep()
system calls used in process management.
4. int main()
This is the entry point of the program where the execution starts.
6. int pid=fork();
Here, the fork() system call is used to create a new process. The return value of
fork() is stored in the variable pid:
In the parent process, fork() returns the child’s process ID, a positive integer.
In the child process, fork() returns 0.
7. if (pid>0)
This condition checks if pid is greater than 0, meaning the code is running in the
parent process (since only the parent gets the child’s PID as a return value).
printf("in child process");: After the 5-second sleep, the child process will print
"in child process" to the console.
At this point, the child process continues to run even though its parent has
finished. After the parent terminates, the child process becomes an orphan and is
adopted by the init or systemd process (depending on the operating system).
9. return 0;
This signals the end of the main() function, returning 0 to indicate that the
program executed successfully.
1. #include<stdlib.h>
This header file includes functions for performing general functions like memory
allocation, process control, conversions, etc. It allows the use of exit() to
terminate a process.
2. #include<sys/types.h>
This header defines types like pid_t used in system calls for working with process
IDs.
3. #include<unistd.h>
This includes the POSIX API for system calls like fork() and sleep() used in this
program.
4. #include<stdio.h>
This header file allows for input/output operations, such as printing to the
console using printf().
5. int main()
This is the entry point of the program where execution starts.
6. int child_pid;
Declares an integer variable child_pid, which will store the process ID returned by
the fork() system call.
7. child_pid=fork();
The fork() system call creates a new child process.
The return value of fork() is stored in child_pid.
In the parent process, fork() returns the child's process ID (a positive integer).
In the child process, fork() returns 0.
8. printf("process created");
This prints "process created" to the console in both the parent and the child
process, because both processes continue to execute this line after fork() is
called. However, there might be only one print visible, depending on how the
processes are scheduled.
9. if(child_pid>0)
This checks if child_pid is greater than 0, meaning the code is currently executing
in the parent process.
ROUND ROBIN:
This C program simulates the Round Robin (RR) Scheduling Algorithm used in process
scheduling. Let's go through the code step by step:
1. #include<stdio.h>
This includes the Standard Input/Output library, which allows using functions like
printf() and scanf() for console input/output operations.
2. #include<conio.h>
This includes the Console Input/Output library, which provides console input/output
functions like getch(). This library is specific to certain compilers (like Turbo
C), and it's not necessary for standard C programs in modern environments.
3. void main()
This is the entry point of the program. In C, int main() is more standard, but void
main() works in some environments.
4. int i, NOP, sum=0, count=0, y, quant, wt=0, tat=0, at[10], bt[10], temp[10];
i: A loop variable.
NOP: Number of processes.
sum: Keeps track of the total time as processes are executed.
count: Used to track if a process has completed execution in the current round.
y: A copy of NOP to track the remaining processes.
quant: The time quantum for the round-robin scheduling.
wt: Total waiting time of all processes.
tat: Total turnaround time of all processes.
at[10]: Array to store the arrival times of up to 10 processes.
bt[10]: Array to store the burst times of up to 10 processes.
temp[10]: Temporary array to store the remaining burst times of the processes.
5. printf(" Total number of process in the system: ");
This prompts the user to enter the total number of processes in the system.
6. scanf("%d", &NOP);
This reads the number of processes from the user and stores it in the variable NOP.
7. y = NOP;
This assigns the value of NOP to y. This is used to track the remaining processes
as y decreases when processes are completed.
9. printf("\n Enter the Arrival and Burst time of the Process[%d]\n", i+1);
This prompts the user to enter the arrival time and burst time for each process,
starting from Process 1.
15. printf("\n Process No \t\t Burst Time \t\t TAT \t\t Waiting Time ");
This prints the table header for displaying process information such as Process
Number, Burst Time, Turnaround Time (TAT), and Waiting Time.
19. temp[i] = 0;
This sets the remaining burst time of the current process to 0, indicating that it
has finished.
20. count=1;
This indicates that the current process has finished execution.
25. y--;
This decrements the number of remaining processes (y), indicating that one more
process has completed.
26. printf("\nProcess No[%d] \t\t %d \t\t\t %d \t\t\t %d", i+1, bt[i], sum-at[i],
sum-at[i]-bt[i]);
This prints the process number, burst time, turnaround time (sum - at[i]), and
waiting time (sum - at[i] - bt[i]).
29. count = 0;
This resets the count variable for the next iteration.
31. i = 0;
If the last process has been reached, the loop resets i to 0 to start the next
round.
33. i++;
If the next process has arrived, the loop proceeds to the next process.
34. else { i = 0; }
If the next process hasn't arrived yet, the loop resets i to 0 to continue
checking.
39. getch();
This waits for the user to press a key before closing the program. It's specific to
older environments like Turbo C and is not required in modern C programs.
Summary:
This program simulates Round Robin Scheduling, where:
FCFS:
This C program implements First-Come, First-Served (FCFS) scheduling for processes,
calculating the waiting time (WT) and turnaround time (TAT) for each process. Let's
go through the code step by step:
1. #include<stdio.h>
This includes the Standard Input/Output library, which allows using functions like
printf() and scanf() for console input/output operations.
2. #include<conio.h>
This includes the Console Input/Output library, which provides console I/O
functions like getch(). This is optional and mainly used in older environments like
Turbo C.
3. int main()
This is the entry point of the program.
4. int pid[15];
An array pid[] is declared to store the process IDs for up to 15 processes.
5. int bt[15];
An array bt[] is declared to store the burst times (execution times) for up to 15
processes.
6. int n;
This variable n is used to store the number of processes.
8. scanf("%d",&n);
This reads the number of processes (n) from the user.
9. printf("enter process id for all processes:");
This prompts the user to enter the process IDs.
14. wt[0]=0;
The waiting time for the first process is always 0, as it doesn't have to wait for
any prior process to finish.
18. for(i=0;i<n;i++)
This loop iterates over all processes to calculate and print individual waiting and
turnaround times.
Explanation of Terms:
Waiting Time (WT):
The time a process has to wait before it gets the CPU.
Calculated as WT[i] = sum of burst times of previous processes.
Turnaround Time (TAT):
The total time taken from the submission of a process to its completion.
Calculated as TAT[i] = WT[i] + BT[i].
Example:
Suppose you input:
Number of processes: 3
Process IDs: 1, 2, 3
Burst times: 5, 8, 12
The output will be:
css
Copy code
Process ID Burst Time Waiting Time Turnaround Time
1 5 0 5
2 8 5 13
3 12 13 25
SJF:
This C program implements Shortest Job First (SJF) scheduling in non-preemptive
mode, where processes are sorted by their burst times (execution times). Here's a
detailed breakdown of the code, step by step:
1. #include <stdio.h>
This includes the Standard Input/Output library for using printf() and scanf()
functions for console operations.
2. int main()
The main() function is the entry point of the program.
3. Variable Declarations:
c
Copy code
int bt[20], p[20], wt[20], tat[20], i, j, n, total = 0, pos, temp;
float avg_wt, avg_tat;
bt[20]: Array to store the burst times of up to 20 processes.
p[20]: Array to store the process IDs.
wt[20]: Array to store the waiting times.
tat[20]: Array to store the turnaround times.
i, j: Loop counters.
n: Number of processes.
total: Accumulates the total waiting and turnaround times for average calculation.
pos: Used for tracking the position of the shortest burst time in the selection
sort algorithm.
temp: Temporary variable used for swapping values during sorting.
avg_wt, avg_tat: Variables to store the average waiting time and average turnaround
time.
4. User Input:
c
Copy code
printf("Enter number of processes: ");
scanf("%d",&n);
This part asks the user to input the number of processes (n).
Process ID
Burst Time
Waiting Time
Turnaround Time for each process.
11. Display Average Times:
c
Copy code
printf("\nAverage Waiting Time: %.2f", avg_wt);
printf("\nAverage Turnaround Time: %.2f", avg_tat);
This prints the average waiting time and average turnaround time with two decimal
places.
Summary of Important Terms:
Waiting Time (WT):
A CPU scheduling algorithm that selects the process with the shortest burst time
next.
Non-preemptive SJF executes each process fully before moving to the next.
SEMAPHORE:
This program demonstrates multithreading using POSIX threads (pthreads) and
semaphores to synchronize access to a shared variable between two threads. Here's a
line-by-line explanation:
3. Global Variables:
c
Copy code
int shared = 1; // A global shared variable
sem_t s; // A semaphore to control access to the shared variable
shared: A global variable that both threads will access and modify.
sem_t s: A semaphore that will be used to ensure that the two threads do not access
shared simultaneously, preventing a race condition.
4. Main Function:
c
Copy code
int main() {
sem_init(&s, 0, 1); // Initialize the semaphore with an initial value of 1
sem_init(&s, 0, 1) initializes the semaphore s with an initial value of 1. This
allows one thread to enter the critical section while the other waits.
0: Specifies that the semaphore is shared between threads (not processes).
1: The initial value of the semaphore.
c
Copy code
pthread_t thread1, thread2; // Declare two thread identifiers
pthread_t thread1, thread2: Declare two threads, thread1 and thread2.
c
Copy code
pthread_create(&thread1, NULL, fun1, NULL);
pthread_create(&thread2, NULL, fun2, NULL);
pthread_create creates two threads:
thread1 will execute the fun1 function.
thread2 will execute the fun2 function.
c
Copy code
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join is used to wait for the threads thread1 and thread2 to finish before
proceeding. This ensures that the main function does not terminate before both
threads complete execution.
c
Copy code
printf("Final value of shared is %d \n", shared);
This prints the final value of the shared variable after both threads have
completed their work.
c
Copy code
sem_destroy(&s); // Destroy the semaphore to free resources
return 0;
}
sem_destroy(&s) destroys the semaphore, freeing its resources.
5. Thread Function fun1:
c
Copy code
void* fun1(void* arg) {
int x;
sem_wait(&s); // Wait (decrement) semaphore to enter critical section
sem_wait(&s) is called to lock the semaphore (decrement its value). If the
semaphore is already locked by another thread, this thread will block until it can
acquire the lock.
c
Copy code
x = shared; // Read the shared variable
printf("Thread 1 reads the value as %d \n", x);
x = shared copies the current value of the shared variable shared into the local
variable x.
The current value is printed.
c
Copy code
x++;
printf("Local updation by thread 1: %d \n", x);
sleep(1); // Simulate some processing time
x++ increments the local copy of shared.
sleep(1) pauses the thread for 1 second to simulate some processing time.
c
Copy code
shared = x; // Update the global shared variable
printf("Value of shared variable updated by thread 1 is: %d \n", shared);
The global shared variable is updated with the new value of x.
The updated value of shared is printed.
c
Copy code
sem_post(&s); // Signal (increment) semaphore to leave critical section
return NULL;
}
sem_post(&s) increments the semaphore value, allowing other threads to access the
critical section.
return NULL ends the function.
6. Thread Function fun2:
c
Copy code
void* fun2(void* arg) {
int y;
sem_wait(&s); // Wait (decrement) semaphore to enter critical section
Similar to fun1, sem_wait(&s) locks the semaphore, blocking other threads.
c
Copy code
y = shared; // Read the shared variable
printf("Thread 2 reads the value as %d \n", y);
y = shared reads the current value of shared and stores it in the local variable y.
The value is printed.
c
Copy code
y++;
printf("Local updation by thread 2: %d \n", y);
sleep(1); // Simulate some processing time
y++ increments the local copy of the shared variable.
The thread is paused for 1 second.
c
Copy code
shared = y; // Update the global shared variable
printf("Value of shared variable updated by thread 2 is: %d \n", shared);
The global shared variable is updated with the incremented value y.
The updated value is printed.
c
Copy code
sem_post(&s); // Signal (increment) semaphore to leave critical section
return NULL;
}
sem_post(&s) releases the semaphore, allowing other threads to access the shared
variable
SHELL SCRIPT:
FACTORIAL OF GV NUM USING FOR LOOP:
This is a Bash script to calculate the factorial of a number entered by the user.
Let me explain the script line by line:
mathematica
Copy code
Enter a number
5
Factorial of 5: 120
Explanation of the Factorial Calculation:
For num = 5, the loop goes through:
Iteration 1: fact = 1 * 1 = 1
Iteration 2: fact = 1 * 2 = 2
Iteration 3: fact = 2 * 3 = 6
Iteration 4: fact = 6 * 4 = 24
Iteration 5: fact = 24 * 5 = 120
The final value of fact after the loop is 120, which is the factorial of 5.
1. String Declaration:
bash
Copy code
str="operating system lab"
str="operating system lab": This initializes the variable str with the value
"operating system lab", which is the string whose length you want to calculate.
2. Length Calculation:
bash
Copy code
length=${#str}
length=${#str}: This syntax calculates the length of the string stored in the
variable str. The ${#str} expression returns the number of characters in the
string.
3. Printing the Result:
bash
Copy code
echo "Length of '$str' is $length"
echo "Length of '$str' is $length": This prints the string "Length of 'operating
system lab' is" followed by the length stored in the length variable.
Example Output:
For the string "operating system lab", the output would be:
csharp
Copy code
Length of 'operating system lab' is 20
Explanation:
The string "operating system lab" has 20 characters, including spaces, so the
script correctly calculates and outputs the length as 20.
Step-by-Step Explanation
Print a Message:
bash
Copy code
echo "Reverse the given number using while loop"
This line outputs a message to the console informing the user about the purpose of
the script.
bash
Copy code
echo "Enter a number"
This line prompts the user to enter a number that they want to reverse.
Read Input:
bash
Copy code
read num
The read command takes input from the user and stores it in the variable num.
bash
Copy code
reverse=0
This line initializes a variable reverse to 0. This variable will hold the reversed
number as we compute it.
While Loop:
bash
Copy code
while [ $num -gt 0 ]; do
This begins a while loop that continues as long as num is greater than 0.
Calculate Remainder:
bash
Copy code
remainder=$(($num % 10))
Inside the loop, this line calculates the remainder when num is divided by 10. This
gives the last digit of the number. The $(...) syntax executes the expression
inside and stores the result in remainder.
bash
Copy code
reverse=$(($reverse * 10 + $remainder))
This line updates the reverse variable by multiplying it by 10 (shifting the
existing digits to the left) and adding the remainder (the last digit of num). This
builds the reversed number step by step.
bash
Copy code
num=$(($num / 10))
This line removes the last digit from num by dividing it by 10. It prepares num for
the next iteration of the loop.
bash
Copy code
done
This marks the end of the while loop. The loop will repeat until num becomes 0.
bash
Copy code
echo "Reversed number is: $reverse"
Finally, this line outputs the reversed number stored in the reverse variable.
Summary
The script effectively takes a number from the user, reverses it digit by digit
using a while loop, and prints the reversed number. The key operations involve
calculating the remainder and updating both the reverse and num variables until all
digits are processed.
If you have any questions about specific parts of the code or if you want to
explore more examples, feel free to ask!
Step-by-Step Explanation
Initialize the String:
bash
Copy code
s="operating system lab"
This line defines a variable s and assigns it the string "operating system lab".
bash
Copy code
strlen=${#s}
Here, ${#s} is used to get the length of the string s, and the result is stored in
the variable strlen.
bash
Copy code
revstr=""
This line initializes an empty string variable revstr, which will be used to store
the reversed version of s.
For Loop:
bash
Copy code
for((i=$strlen-1;i>=0;i--)); do
This line starts a for loop that begins at the last index of the string (strlen -
1) and decrements i until it reaches 0. This allows the loop to iterate over each
character of the string in reverse order.
bash
Copy code
revstr+=${s:$i:1}
Inside the loop, this line extracts a single character from s at the index i using
${s:$i:1} and appends it to revstr. The += operator is used to concatenate the
character to the end of revstr.
bash
Copy code
done
This marks the end of the for loop. The loop will continue until all characters
have been processed.
bash
Copy code
echo "Original string: $s"
echo "Reversed string: $revstr"
Finally, these lines output the original string and the reversed string. The
variable s holds the original string, while revstr contains the reversed version.
Summary
The script effectively takes a string, reverses it character by character using a
for loop, and prints both the original and reversed strings. The key operations
involve calculating the length of the string and iterating over its characters in
reverse order to build the reversed string.
Example Output
For the string "operating system lab", the output would be:
c
Copy code
Original string: operating system lab
Reversed string: bal metsys gnitaro
If you have any questions about specific parts of the code or if you'd like to see
variations or more examples, feel free to ask!
Step-by-Step Explanation
Prompt for Input:
bash
Copy code
echo "Enter a string"
This line prints a message to the console asking the user to enter a string.
Read Input:
bash
Copy code
read string
The read command takes input from the user and stores it in the variable string.
bash
Copy code
if [[ $string =~ ^[a-zA-Z]+$ ]]; then
This line uses a conditional statement to check if the string matches a specific
pattern:
If Condition True:
bash
Copy code
echo "String contains only alphabets"
If the condition is true (i.e., the string contains only letters), this line prints
a message indicating that the string is valid.
If Condition False:
bash
Copy code
else
echo "String does not contain only alphabets"
fi
If the condition is false (i.e., the string contains characters other than
letters), this block executes and prints a message indicating that the string is
invalid.
Summary
The script effectively prompts the user for a string and checks whether it contains
only alphabetic characters using a regular expression. It outputs a message
indicating the validity of the string based on the check.
Example Output
If the user inputs HelloWorld:
sql
Copy code
String contains only alphabets
If the user inputs Hello123:
arduino
Copy code
String does not contain only alphabets
SUBJECT DETAILS:
Let's break down the provided shell script step by step. This script collects and
prints details about a subject for a specific paper.
Step-by-Step Explanation
Print Header:
bash
Copy code
echo "III BSC CS-SBE Paper"
This line outputs a header indicating the title or context of the information that
will follow, in this case, "III BSC CS-SBE Paper".
bash
Copy code
echo "Enter the subject code: "
read code
The first echo command prompts the user to enter the subject code.
The read code command takes the user's input and stores it in the variable code.
Prompt for Subject Name:
bash
Copy code
echo "Enter the subject name: "
read name
Similarly, this echo command prompts the user for the subject name.
The read name command captures the input and stores it in the variable name.
Print Paper Details:
bash
Copy code
echo "\nSBE Paper Details:"
echo "Subject Code: $code"
echo "Subject Name: $name"
The first line intends to print a label "SBE Paper Details:", but the \n will not
work as intended in echo. To include a new line, you can either use echo -e (which
enables interpretation of backslash escapes) or just separate the two echo
commands:
bash
Copy code
echo -e "\nSBE Paper Details:"
or
bash
Copy code
echo ""
echo "SBE Paper Details:"
The next two lines print the subject code and subject name using the variables
$code and $name, respectively.
Summary
The script prompts the user to enter a subject code and subject name, then prints
those details as part of the "SBE Paper Details." The final output will summarize
the entered information.
Step-by-Step Explanation
Prompt for Input:
bash
Copy code
echo "Enter two strings to check whether they are equal"
This line prints a message to inform the user that they will be prompted to enter
two strings for comparison.
bash
Copy code
read -p "String 1: " str1
The read command here uses the -p option to prompt the user with "String 1: ".
The input is captured and stored in the variable str1.
Read Second String:
bash
Copy code
read -p "String 2: " str2
This line also uses the read command with the -p option to prompt the user for the
second string with "String 2: ".
The input is stored in the variable str2.
String Comparison:
bash
Copy code
if [ "$str1" == "$str2" ]; then
This line starts an if statement to compare the two strings.
The condition checks whether str1 is equal to str2 using ==.
The double quotes around the variables ensure that the comparison works even if the
strings contain spaces or are empty.
If Condition True:
bash
Copy code
echo "Both strings are equal"
If the condition evaluates to true (the strings are equal), this line executes and
prints a message indicating that the strings are equal.
If Condition False:
bash
Copy code
else
echo "Both strings are not equal"
fi
If the condition evaluates to false (the strings are not equal), this block
executes and prints a message indicating that the strings are not equal.
Summary
The script prompts the user for two strings, compares them, and outputs whether
they are equal or not.
Example Output
Assuming the user inputs:
String 1: hello
String 2: hello
The output will be:
sql
Copy code
Both strings are equal
If the user inputs:
String 1: hello
String 2: world
The output will be:
sql
Copy code
Both strings are not equal
Suggested Improvement
To make the string comparison more robust and compatible with different shells, you
might consider using = instead of ==, which is more widely supported in POSIX-
compliant shells:
bash
Copy code
if [ "$str1" = "$str2" ]; then
[22/10/2024 11:21 AM] : Here are some common abbreviations used in C programming,
particularly with the stdio.h library:
stdio.h Functions:
Data Types:
1. int - Integer
2. char - Character
3. float - Floating-point number
4. double - Double-precision floating-point number
Operators:
1. = - Assignment
2. == - Equal to
3. != - Not equal to
4. > - Greater than
5. < - Less than
6. >= - Greater than or equal to
7. <= - Less than or equal to
8. + - Addition
9. - - Subtraction
10. * - Multiplication
11. / - Division
12. % - Modulus (remainder)
Control Structures:
1. if - If statement
2. else - Else statement
3. for - For loop
4. while - While loop
5. do - Do-while loop
6. switch - Switch statement
7. case - Case statement
8. break - Break statement
9. continue - Continue statement
Other:
These abbreviations are commonly used in C programming and can help improve code
readability and writing efficiency.
[22/10/2024 11:21 AM] : The full form of stdio.h is:
- con: Console
- io: Input/Output
- .h: Header file
[22/10/2024 11:23 AM] : The name sys/types.h is derived from:
- uni: Unix
- std: Standard
- .h: Header file
[22/10/2024 11:24 AM] : The name stdlib.h is derived from:
- std: Standard
- lib: Library
- .h: Header file