0% found this document useful (0 votes)
45 views

Final SE314L review

se314

Uploaded by

msiddiquesamia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Final SE314L review

se314

Uploaded by

msiddiquesamia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Lab 2: Linux Commands

1. Important Commands to Know:


o date:

 Displays the current date and time.


 Example: date +"%A, %d %B %Y %H:%M:%S"
o cal:

 Displays a calendar.
 Example: cal 2024 (Year) or cal 12 2024 (Specific month).
o echo:

 Prints text to the terminal.


 Example: echo "Hello, World!"
o banner:

 Displays text in a large, stylized format.


 Example: banner "OS Lab"
o who:

 Shows logged-in users.


 Example: who -H
o tty:

 Displays the terminal name.


 Example: tty
o man:

 Displays the manual for a command.


 Example: man ls
2. Exam Focus:
o Your instructor might give you a specific man command, and you need to interpret
the output (e.g., man mkdir).
Lab 3: File Commands and Basic C
1. Linux File Commands:
o pwd: Print the current working directory.

o ls: List all files and directories.

o mkdir <folder_name>: Create a directory.

o cd <folder_name>: Navigate to a directory.

o pico <file_name>: Create or edit a file.

2. Compiling and Running C Code:


o Compile:

gcc <file_name>.c -o <output_name>


o Run:

./<output_name>

Lab 4: Advanced C Programming


1. Printing Addresses and Values:
o Printing Address:

printf("Address: %p\n", &x);


o Printing Value Using a Pointer:

int x = 5;
int *ptr = &x;
printf("Value: %d\n", *ptr);
2. Command-Line Arguments:
o Example:

int main(int argc, char *argv[]) {


printf("Argument count: %d\n", argc);
printf("First argument: %s\n", argv[1]);
}
Lab 5: Process Creation
1. Process ID (PID):
o Use getpid() to get the current process ID.

o Use getppid() to get the parent process ID.

2. Key Concepts:
o Parent and Child Processes: Created using fork().

o wait(): Makes the parent wait for the child to finish.

3. Finding a Program in ps:


o Run:

ps -u <username>

Lab 6: Fork, Sleep, and Process Terminology


1. Key Functions:
o fork(): Creates a new process.

o sleep(seconds): Pauses execution for a specific time.

2. Orphan Processes:
o If a parent dies, the child is adopted by the init process.

3. Zombie Processes:
o A child process that has terminated but its parent hasn’t collected its exit code using
wait().
4. Terminology:
o Parent Process: The process that creates a child.

o Child Process: The newly created process.

o Orphan Process: A child whose parent has died.

o Zombie Process: A terminated process not collected by its parent.

Lab 7: Threads
1. Key Points:
o Threads share global memory but not local memory.

o Processes do not share any memory.


2. Parameters of pthread_create:
o First parameter: Pointer to the thread ID.

o Third parameter: Pointer to the function the thread will execute.

3. Race Conditions:
o Occurs when multiple threads access shared resources simultaneously without
synchronization.

Lab 8: Mutex Locks


1. Mutex Initialization:
o Always initialize in the main method:

pthread_mutex_t lock;
pthread_mutex_init(&lock, NULL);
2. Fixing Race Conditions:
o Use mutex locks to protect critical sections:

pthread_mutex_lock(&lock);
// Critical section
pthread_mutex_unlock(&lock);

Lab 9: Semaphores
1. Key Concepts:
o Semaphores are used for synchronization.

o Know sem_init, sem_wait, sem_post, and sem_destroy.

2. Initialization Example:
sem_t semaphore;
sem_init(&semaphore, 0, 1); // Binary semaphore

Lab 10: File System Calls


1. Key Functions:
o creat(): Create a file.

o open(): Open a file.

o read(): Read data from a file.


o write(): Write data to a file.

o lseek(): Move the file pointer.

2. Example to Open, Write, and Read:


int fd = open("file.txt", O_RDWR | O_CREAT, 0666);
write(fd, "Hello", 5);
char buffer[10];
read(fd, buffer, 5);
printf("%s\n", buffer);
close(fd);
3. Key Points:
o Be ready to write code based on these functions.

o lseek: Moves the file pointer (e.g., to append or overwrite).

Study Tips:
1. Review all the codes in Lab 10 thoroughly.
2. Practice writing pseudocode for process and thread operations.
3. Understand the concepts of race conditions, mutex locks, and semaphores through examples.
4. Focus on how to interpret commands and code outputs for Labs 2, 3, and 5.
5. Memorize the purpose and usage of key system calls for file management in Lab 10.
Study Steps
1. Understand Concepts
 Lab 2 (Linux Commands):
o Purpose of each command (date, cal, echo, banner, who, tty, man).

o Be ready to use man to look up specific commands and interpret the manual's
sections, such as:
 Name: What the command does.
 Syntax: How the command is structured.
 Options: Flags that modify the behavior of the command.
 Lab 3 (File Commands and Basic C):
o Practice basic file commands (pwd, ls, mkdir, cd).

o Learn how to compile (gcc) and run C code.

 Lab 4 (Pointers and Command-Line Arguments):


o Understand pointers (& for address, * for dereference).

o Practice writing and interpreting programs with command-line arguments.

 Lab 5 (Process Creation):


o Know how to use getpid() and getppid() to retrieve process IDs.

o Understand the parent-child relationship in processes created with fork().

 Lab 6 (Fork, Sleep, Orphan, Zombie):


o Grasp what happens in fork() and sleep() calls.

o Recognize orphan and zombie processes in scenarios.

 Lab 7 (Threads):
o Understand how threads share global memory but not local memory.

o Be able to write or trace code using pthread_create.

 Lab 8 (Mutex Locks):


o Know how to initialize and use mutex locks to prevent race conditions.

 Lab 9 (Semaphores):
o Understand semaphore operations (sem_init, sem_wait, sem_post).

o Recognize initialization values and their effects in synchronization.

 Lab 10 (File System Calls):


o Learn the purpose of creat(), open(), read(), write(), and lseek().

o Be able to write and understand file operations in code.

2. Practice Writing Code


1. Open a text editor (e.g., VS Code, nano) or an IDE and write down the code examples from
the lab.
2. Compile the code using gcc:
gcc <filename>.c -o <outputname>
3. Run the code:
./<outputname>
4. Modify the code:
o Add print statements to debug and understand the flow.

o Change values and observe the output.

o For example, in Lab 6 (Fork), try adding multiple fork() calls and track the processes
created.
5. Create new code:
o Write a program that combines multiple concepts, such as creating a file, writing to it,
and reading from it using system calls (Lab 10).

3. Solve Scenarios
Example Scenarios:
1. Lab 6:
o "A child process sleeps for 3 seconds while the parent terminates. What happens to
the child?"
 Answer: It becomes an orphan and is adopted by the init process.
2. Lab 7:
o "Two threads are incrementing a shared variable without synchronization. What
happens?"
 Answer: A race condition occurs, causing unpredictable results.
3. Lab 10:
o "Open a file, write 'Hello', and then read it back. Write pseudocode."

fd = open("file.txt", O_RDWR | O_CREAT, 0666);


write(fd, "Hello", 5);
lseek(fd, 0, SEEK_SET);
read(fd, buffer, 5);
printf("%s", buffer);
close(fd);

4. Interpret Commands and Outputs


Linux Commands:
1. What does this command do?
echo "Hello" > file.txt
o Answer: Writes "Hello" into file.txt, overwriting any existing content.

2. What does this man output mean?


o Example for ls:

ls [OPTION]... [FILE]...
o Answer: The square brackets indicate optional arguments. The ls command can be used
alone or with options (e.g., -l for detailed listing).
Code Snippets:
1. What does this code do?
int fd = open("data.txt", O_RDWR | O_CREAT, 0666);
write(fd, "OS Lab", 6);
o Answer: Opens or creates data.txt with read/write permissions and writes "OS Lab"
into it.
2. What happens here?
pthread_create(&tid, NULL, &my_function, NULL);
o Answer: Creates a new thread, where tid is the thread ID, and my_function is the
function executed by the thread.

5. Memorize Key Functions and Syntax


Quick Reference:
 Fork and Process Functions:
o fork(): Creates a new process.

o getpid(): Gets the process ID.

o getppid(): Gets the parent process ID.

 Thread Functions:
o pthread_create: Creates a thread.

o pthread_mutex_lock: Locks a critical section.


o pthread_mutex_unlock: Unlocks a critical section.

 File System Calls:


o open: Opens or creates a file.

o write: Writes data to a file.

o read: Reads data from a file.

o lseek: Moves the file pointer.


Mock Exam

Lab 2: Linux Commands


1. True or False:
a. The echo command can be used to display text and save it directly to a file.

b. The banner command displays text as large characters made of # symbols.

2. Commands and Interpretation:


a. What does the following command do?
echo "OS Final" > file.txt

b. Write the command to display the current date and time in the format: DD-MM-YYYY.

c. Explain the output of the following command:


cal 12 2024

3. Manual Interpretation:
Your instructor asks you to check the man page of the mkdir command. What does the
following section mean?
mkdir [OPTION]... DIRECTORY...
-p, --parents no error if existing, make parent directories as needed
Write your explanation.

4. Write the command to:


a. Display the users currently logged in.

b. Clear the terminal screen.


Lab 3: File Commands and Basic C
1. True or False:
a. The pwd command shows the list of files in the current directory.

b. The mkdir command is used to create a new file.

2. Commands:
a. Write the sequence of commands to:
o Create a directory named test_folder.

o Navigate into test_folder.

o Create a text file named test_file.txt using pico.

b. You are asked to list all files and folders in your current directory, including hidden files.
Write the command.

3. C Programming:
a. Write the steps to compile and execute the following C code:
#include<stdio.h>
int main() {
printf("Hello, OS Lab!\n");
return 0;
}
b. What will happen if you run the above code without compiling it first?

Lab 4: Advanced C Programming


1. True or False:
a. The & operator in C is used to get the value stored in a pointer.

b. Command-line arguments are stored in the argv array.

2. Pointers:
a. Write the output of the following code snippet:
int x = 10;
int *ptr = &x;
printf("Address of x: %p\n", &x);
printf("Value of x using pointer: %d\n", *ptr);

b. Modify the code above to update the value of x through the pointer ptr.

3. Command-Line Arguments:
Write a program that takes two numbers as command-line arguments and prints their sum.
Provide the steps to compile and run the program.
Lab 5: Process Creation
1. True or False:
a. The fork() function creates a new child process and assigns it a unique PID.

b. A parent process automatically waits for its child process to finish execution.

2. Process IDs:
a. Write a program to print the process ID (PID) of the current process and its parent process.

b. Explain what happens when the following program is run:


int pid = fork();
if (pid == 0) {
printf("I am the child process.\n");
} else {
printf("I am the parent process.\n");
}

3. Finding Processes:
a. Write the command to display all processes running under the user os_student.

Lab 6: Fork, Sleep, and Process Terminology


1. True or False:
a. A zombie process is created when a child terminates but the parent does not wait for it.

b. Orphan processes are automatically adopted by the init process.


2. Scenarios:
a. What happens if a parent process terminates before its child process?

b. Describe the output of the following code snippet:


int pid = fork();
if (pid == 0) {
sleep(3);
printf("Child process.\n");
} else {
printf("Parent process.\n");
}

3. Pseudocode:
Write pseudocode to create a child process, make the parent process wait for the child to
complete, and then terminate both.
Lab 7: Threads
1. True or False:
a. Threads in the same process share global memory but not local memory.

b. Processes share both global and local memory.

2. Thread Creation:
Write a program that creates a thread to print "Hello from the thread!" and another thread to
print "Goodbye from the thread!". Ensure the main program waits for both threads to
complete.

3. Trace the Program:


Analyze the following program and write the expected output:
void *print_message(void *arg) {
printf("%s\n", (char *)arg);
return NULL;
}
int main() {
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, print_message, "Hello, Thread 1");
pthread_create(&tid2, NULL, print_message, "Hello, Thread 2");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
Lab 8: Mutex Locks
1. True or False:
a. Mutex locks are used to prevent race conditions in multithreaded programs.

b. Mutex locks can be initialized in any thread.

2. Fixing Race Conditions:


a. The following code has a race condition. Fix it using a mutex lock.
int counter = 0;
void *increment(void *arg) {
for (int i = 0; i < 1000; i++) {
counter++;
}
return NULL;
}

3. Initialization:
Write the code to initialize a mutex lock in the main function.
Lab 9: Semaphores
1. True or False:
a. A semaphore with an initial value of 1 can only be accessed by one thread at a time.

b. The sem_wait operation increments the semaphore value.

2. Scenarios:
a. A semaphore is initialized to 0. What happens when a thread calls sem_wait on it?

b. Write a code snippet to initialize a semaphore with value 1, decrement it in one thread, and
increment it in another.

Lab 10: File System Calls


1. True or False:
a. The open system call can create a file if it does not exist.

b. The lseek system call is used to delete a file.

2. File Operations:
a. Write a program to:
o Create a file named test.txt.

o Write "Operating Systems" into the file.

o Read the content and print it to the terminal.


b. Explain what the following code does:
int fd = open("data.txt", O_RDWR | O_CREAT, 0666);
lseek(fd, 5, SEEK_SET);
write(fd, "Test", 4);
ANSWERS:
Lab 2: Linux Commands
1. True or False:
o a. True – The echo command can display text and redirect it to a file using >.

o b. True – The banner command displays text in large, stylized characters.

2. Commands and Interpretation:


o a. echo "OS Final" > file.txt writes "OS Final" into a file named file.txt, overwriting
its contents if it exists.
o b. date +"%d-%m-%Y" displays the date in DD-MM-YYYY format.

o c. cal 12 2024 displays the calendar for December 2024.

3. Manual Interpretation:
o mkdir [OPTION]... DIRECTORY...: This means that the mkdir command creates a
directory. The -p flag ensures no error occurs if the directory exists, and it creates
parent directories as needed.
4. Commands:
o a. who or who -H displays logged-in users.

o b. clear clears the terminal screen.

Lab 3: File Commands and Basic C


1. True or False:
o a. False – The pwd command prints the current working directory.

o b. True – The mkdir command creates a new directory.

2. Commands:
o a. Commands:

mkdir test_folder
cd test_folder
pico test_file.txt
o b. ls -a lists all files, including hidden files.

3. C Programming:
o a. Steps:
1. Save the code in a file, e.g., hello.c.
2. Compile it: gcc hello.c -o hello.
3. Run it: ./hello.
o b. If you try to run it without compiling, the system will return an error indicating the
file is not executable.

Lab 4: Advanced C Programming


1. True or False:
o a. False – The & operator in C gets the address of a variable, not its value.

o b. True – Command-line arguments are stored in the argv array.

2. Pointers:
o a. Output:

Address of x: <some memory address>


Value of x using pointer: 10
o b. Modified code:

int x = 10;
int *ptr = &x;
*ptr = 20;
printf("Updated value of x: %d\n", x);
3. Command-Line Arguments:
o Code:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: program <num1> <num2>\n");
return 1;
}
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);
printf("Sum: %d\n", num1 + num2);
return 0;
}
o Compile: gcc sum.c -o sum

o Run: ./sum 5 10

Lab 5: Process Creation


1. True or False:
o a. True – fork() creates a child process with a unique PID.

o b. False – A parent process continues execution unless explicitly waiting for the
child.
2. Process IDs:
o a. Program:

#include <stdio.h>
#include <unistd.h>
int main() {
printf("Current PID: %d\n", getpid());
printf("Parent PID: %d\n", getppid());
return 0;
}
o b. Explanation:

 The parent prints "I am the parent process."


 The child prints "I am the child process."
3. Finding Processes:
o Command: ps -u os_student

Lab 6: Fork, Sleep, and Process Terminology


1. True or False:
o a. True – A zombie process occurs when a child terminates, but the parent does not
wait.
o b. True – Orphan processes are adopted by the init process.

2. Scenarios:
o a. The child becomes an orphan and is adopted by the init process.

o b. Output:
Parent process.
Child process. (after 3 seconds)

3. Pseudocode:
fork()
if child:
print("Child process")
exit()
else:
wait()
print("Parent process")

Lab 7: Threads
1. True or False:
o a. True – Threads share global memory but not local memory.

o b. False – Processes do not share memory.

2. Thread Creation:
o Code:

#include <pthread.h>
#include <stdio.h>
void *print_hello(void *arg) {
printf("%s\n", (char *)arg);
return NULL;
}
int main() {
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, print_hello, "Hello from thread 1!");
pthread_create(&tid2, NULL, print_hello, "Goodbye from thread 2!");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}

3. Trace the Program:


o Output:

Hello, Thread 1
Hello, Thread 2
(Order may vary due to thread scheduling.)

Lab 8: Mutex Locks


1. True or False:
o a. True – Mutex locks prevent race conditions.

o b. False – Mutex locks must be initialized before use.

2. Fixing Race Conditions:


o Fixed Code:

pthread_mutex_t lock;
pthread_mutex_init(&lock, NULL);
void *increment(void *arg) {
for (int i = 0; i < 1000; i++) {
pthread_mutex_lock(&lock);
counter++;
pthread_mutex_unlock(&lock);
}
return NULL;
}
3. Initialization:
pthread_mutex_t lock;
pthread_mutex_init(&lock, NULL);

Lab 9: Semaphores
1. True or False:
o a. True – A semaphore with an initial value of 1 allows one thread at a time.

o b. False – sem_wait decrements the semaphore.

2. Scenarios:
o a. If sem_wait is called on a semaphore initialized to 0, the calling thread blocks until
another thread increments it using sem_post.
o b. Code:

sem_t semaphore;
sem_init(&semaphore, 0, 1);
sem_wait(&semaphore);
// Critical section
sem_post(&semaphore);

Lab 10: File System Calls


1. True or False:
o a. True – open can create a file if it doesn’t exist with the O_CREAT flag.

o b. False – lseek moves the file pointer but doesn’t delete files.

2. File Operations:
o a. Program:

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int fd = open("test.txt", O_RDWR | O_CREAT, 0666);
write(fd, "Operating Systems", 17);
char buffer[20];
lseek(fd, 0, SEEK_SET);
read(fd, buffer, 17);
buffer[17] = '\0';
printf("%s\n", buffer);
close(fd);
return 0;
}

o b. Explanation:

 Opens or creates data.txt.


 Moves the pointer 5 bytes forward.
 Writes "Test" starting from the new pointer position.

You might also like