Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Advanced Operating System Solved Question Paper

The document is an advanced operating system question paper covering various topics including process management, system calls, inter-process communication, and file structures. It includes true/false questions, explanations of system calls, and C programming examples demonstrating concepts like race conditions and process creation. Additionally, it discusses buffer allocation strategies and the circumstances under which processes are swapped out.

Uploaded by

sandipganage88
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Advanced Operating System Solved Question Paper

The document is an advanced operating system question paper covering various topics including process management, system calls, inter-process communication, and file structures. It includes true/false questions, explanations of system calls, and C programming examples demonstrating concepts like race conditions and process creation. Additionally, it discusses buffer allocation strategies and the circumstances under which processes are swapped out.

Uploaded by

sandipganage88
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Advanced Operating System

Question Paper 1

Q1.Solve

A) True or False - Justify


Statement: "The kernel is a separated set of processes that run in parallel to user
processes."
Answer: False
 Justification: The kernel is not a set of separate processes. Instead, it is a single
entity that provides system services, manages resources, and directly interacts
with hardware. It operates in kernel space and handles system calls from user
processes, rather than running as parallel processes.

B) 4 Different Conditions for pid Argument of kill System Call


1. Positive pid: Sends the signal to the process with the given pid.
2. pid = 0: Sends the signal to all processes in the process group of the calling
process.
3. Negative pid (other than -1): Sends the signal to all processes in the process
group with the ID equal to the absolute value of pid.
4. pid = -1: Sends the signal to all processes the user has permission to send
signals to, except for system processes.

C) Difference Between wait and waitpid


1. wait:
o Waits for any child process to terminate.
o Blocks the parent process until a child process exits.
2. waitpid:
o Can wait for a specific child process, based on its PID.
o Allows additional options like non-blocking mode.

D) New File Byte Offset After lseek(fd, 0, 2)


 Answer: The new file byte offset will be set to the end of the file.
 Explanation: The lseek(fd, 0, 2) command moves the file offset to the end of
the file (2 represents SEEK_END).

E) What is a Broken Link?


 A broken link occurs when a symbolic link points to a target file or directory
that no longer exists or has been moved. It is also called a dangling link.

F) How to Open Process ID and Parent Process ID?


 Process ID (PID): Use the system call getpid().
 Parent Process ID (PPID): Use the system call getppid().
G) Output of the Code
#include<stdio.h>
int main() {
if (fork() && (!fork())) {
if (fork() || fork()) {
fork();
}
}
printf("2");
return 0;
}
 Answer: The program will print the number "2" multiple times.
 Reason:
o The fork() function creates new processes. Depending on the
combinations of conditions, multiple child processes will be created.
o Each process, including the original and child processes, executes
printf("2").
o The total number of prints depends on the forks, but in this case, there
will be 8 "2"s printed due to the combination of forks in the nested
conditions.

Q2.Solve

A) I) What is a Process? Explain State Transition Diagram


 Process: A program in execution. It includes the program code, data, and
process control information.
 State Transition Diagram: Represents the states a process goes through
during its execution.
Process States
1. New: Process is being created.
2. Ready: Process is ready to run but waiting for CPU.
3. Running: Process is currently being executed by the CPU.
4. Waiting/Blocked: Process is waiting for an I/O operation or resource.
5. Terminated: Process has completed its execution.
State Transitions
1. New → Ready: When the process is created.
2. Ready → Running: CPU scheduler selects it.
3. Running → Ready: Preempted by the scheduler.
4. Running → Waiting: Waiting for an I/O operation.
5. Waiting → Ready: I/O operation completed.
6. Running → Terminated: Process finishes execution.
Diagram:
New → Ready → Running → Terminated
↘ Waiting ↙
A) II) Three Data Structures for Demand Paging
1. Page Table:
o Stores mapping of virtual addresses to physical memory.
o Includes flags for validity, dirty bit, and reference.
2. Frame Table:
o Tracks available and allocated memory frames.
o Helps manage free frames for incoming pages.
3. Swap Space Map:
o Tracks pages that are swapped to disk.
o Used for loading pages back into memory.

B) Syntax of System Calls


alarm(seconds)
o Purpose: Sets an alarm to send the SIGALRM signal to the process
after a specified number of seconds.
Syntax:
unsigned int alarm(unsigned int seconds);
o Example: alarm(5); sends SIGALRM after 5 seconds.

kill(pid, signal)
o Purpose: Sends a signal to a process or group of processes.
Syntax:
int kill(pid_t pid, int sig);
o Example: kill(1234, SIGTERM); terminates process 1234.

sbrk(increment)
o Purpose: Adjusts the program's data segment size.
Syntax:
void* sbrk(intptr_t increment);
o Example: sbrk(1024); increases the heap by 1024 bytes.

exec()
o Purpose: Replaces the current process image with a new process
image.
Syntax:
int execve(const char *path, char *const argv[], char *const envp[]);
o Example: execve("/bin/ls", args, envp); replaces the process with the
ls program.

fchmod(fd, mode)
o Purpose: Changes the permissions of a file specified by the file
descriptor.
Syntax:
int fchmod(int fd, mode_t mode);
o Example: fchmod(fd, 0644); changes the file permissions to read/write
for owner and read for others.

Q3.Solve

A) I) Fourth Scenario for Buffer Allocation


In buffer allocation strategies, the fourth scenario often refers to hybrid buffering,
which combines characteristics of fixed and variable buffering.
Description:
o A portion of the buffer is allocated as fixed-size blocks for predictable
requests.
o Another portion is allocated dynamically to handle variable or large
requests.
o This ensures both efficiency for standard operations and flexibility for
exceptional cases.

Advantages:
o Combines the strengths of fixed and dynamic allocation.
o Reduces fragmentation.
o Efficient memory usage for diverse workloads.

A) II) Behaviour of the Program


Code Explanation:
Input Argument Check:
o The program expects one command-line argument (argc != 2
condition).
o If not provided, it calls exit() and terminates.

File Reading:
o Opens a file (fd assumed to be initialized to a valid file descriptor).
o Reads one character at a time using read(fd, &c, 1).

Seek Operation:
o Uses lseek(fd, 1023L, SEEK_CUR) to move 1023 bytes forward from
the current position.
o Stores the new position in skval.

Output:
o Prints the character read (char c) and the new seek value (new seek
val).
Behaviour:
 The program reads a file character by character, skipping 1023 bytes after
each character.
 Outputs the read character and the updated file position.
 If the file size is less than the skipped bytes, the program may produce no
output or encounter errors.

B) C Program to Print the Type of File for Each Command Line Argument
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
struct stat fileStat;
if (argc < 2) {
printf("Usage: %s <file1> <file2> ...\n", argv[0]);
exit(1);
}
for (int i = 1; i < argc; i++) {
if (stat(argv[i], &fileStat) < 0) {
perror("stat");
continue;
}
printf("File: %s -> ", argv[i]);
if (S_ISREG(fileStat.st_mode))
printf("Regular File\n");
else if (S_ISDIR(fileStat.st_mode))
printf("Directory\n");
else if (S_ISCHR(fileStat.st_mode))
printf("Character Device\n");
else if (S_ISBLK(fileStat.st_mode))
printf("Block Device\n");
else if (S_ISFIFO(fileStat.st_mode))
printf("FIFO/Named Pipe\n");
else if (S_ISLNK(fileStat.st_mode))
printf("Symbolic Link\n");
else if (S_ISSOCK(fileStat.st_mode))
printf("Socket\n");
else
printf("Unknown File Type\n");
}
return 0;
}
Explanation:
 stat(): Fetches file information.
 File Type Check: Checks st_mode using macros like S_ISREG, S_ISDIR,
etc., to determine the file type.
 Output: Prints the type of each file provided as a command-line argument.
Sample Execution:
./filetype myfile.txt /etc /dev/null
File: myfile.txt -> Regular File
File: /etc -> Directory
File: /dev/null -> Character Device

Q4.Solve

A) I) What are Pipes? Explain Named and Unnamed Pipes


Pipes are a mechanism for inter-process communication (IPC) that allows data to be
transferred between processes.
1. Unnamed Pipes
 Used for communication between parent and child processes.
 Created using the pipe() system call.
 Limited to processes that share a common ancestry.
 Example:
int fd[2];
pipe(fd); // fd[0] for reading, fd[1] for writing

2. Named Pipes (FIFOs)


 Used for communication between unrelated processes.
 Created using the mkfifo() system call or command-line utility.
 Persist as a file in the filesystem.
 Example:
mkfifo("/tmp/myfifo", 0666);
int fd = open("/tmp/myfifo", O_WRONLY);
Comparison:
Feature Unnamed Pipes Named Pipes (FIFO)
Communication Parent-child processes Unrelated processes
Persistence Temporary Persistent
Creation pipe() system call mkfifo() or mknod()

A) II) Operations Performed by Kernel During fork()


The fork() system call creates a new process (child) as a copy of the calling process
(parent). Operations performed include:
Process Control Block (PCB) Creation:
o Creates a new PCB for the child process.

Memory Duplication:
o Duplicates the memory space of the parent process.
o Uses copy-on-write mechanism to optimize memory usage.

Resource Duplication:
o Copies open file descriptors, environment variables, and signal
handlers.

Unique Identifiers:
o Assigns a unique Process ID (PID) to the child process.

B) C Program to Demonstrate Race Condition in Catching Signals


A race condition occurs when multiple processes or threads access shared resources
without proper synchronization, leading to unpredictable behavior. Here's an example
using signal handling:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>

int counter = 0;

void signal_handler(int sig) {


counter++;
printf("Signal received: %d, Counter: %d\n", sig, counter);
}

int main() {
signal(SIGINT, signal_handler); // Handle Ctrl+C (SIGINT)

printf("Press Ctrl+C multiple times to see race condition in counter\n");

while (1) {
pause(); // Wait for signal
}

return 0;
}
Explanation:
 Shared Resource: The counter variable is shared between the main program
and the signal handler.
 Race Condition: If multiple signals are received in quick succession, the
counter variable may not be updated correctly due to lack of synchronization.
Example Execution:
1. Run the program.
2. Press Ctrl+C repeatedly.
3. Observe that counter may increment inconsistently due to a race condition.
Solution: Use proper synchronization mechanisms like sigprocmask() or atomic
variables to prevent race conditions.
Q5.Solve
A) I) Circumstances Under Which a Process is Swapped Out
Swapping is the process of moving a process from main memory to secondary storage
(disk) to free up memory. A process is swapped out under the following
circumstances:
Memory Shortage:
1. If there is insufficient memory to accommodate high-priority or new
processes.

Idle Process:
1. If a process is waiting for I/O operations to complete, it may be
swapped out to allow other processes to execute.

Low-Priority Process:
1. Lower-priority processes are swapped out to allocate resources to
higher-priority processes.

Multiprogramming:
1. To increase the degree of multiprogramming by freeing up memory for
other processes.

A) II) Structure of a Regular File with Suitable Diagram


A regular file in an advanced operating system is organized in a structured way to
store data and metadata.
Components of a Regular File
1. Metadata:
1. Includes information about the file, such as size, permissions, owner,
and timestamps.
2. Data Blocks:
1. Stores the actual content of the file.
3. Indirect Blocks:
1. Pointers to data blocks or additional block pointers for larger files.
Diagram of a File Structure
+------------------+
| Metadata |
| (inode structure)|
+------------------+
| Direct Pointers | -> Data Blocks
+------------------+
| Indirect Pointers| -> Data Blocks or More Pointers
+------------------+

B) C Program to Create a Child Process to Execute Commands


Below is a C program where the parent creates a child process to read and execute
commands:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
char command[100];
pid_t pid;

while (1) {
printf("Enter command to execute (or 'exit' to quit): ");
fgets(command, sizeof(command), stdin);

// Remove newline character from command


command[strcspn(command, "\n")] = 0;

if (strcmp(command, "exit") == 0) {
break;
}

pid = fork();

if (pid == 0) { // Child process


execlp(command, command, NULL);
perror("Error executing command");
exit(1);
} else if (pid > 0) { // Parent process
wait(NULL); // Wait for the child to finish
} else {
perror("Fork failed");
}
}

return 0;
}

Explanation of the Program


Parent Process:
1. Reads a command from standard input.
2. Forks a child process to execute the command.

Child Process:
1. Executes the command using execlp().
2. If the command fails, an error message is printed.

Parent Waits:
1. Parent waits for the child to complete before proceeding to the next
command.

Exit Mechanism:
1. If the user types exit, the loop breaks, and the program terminates.
Sample Execution:
Enter command to execute (or 'exit' to quit): ls
<lists files in directory>
Enter command to execute (or 'exit' to quit): date
<prints current date>
Enter command to execute (or 'exit' to quit): exit

Q6.Solve

A) I) Circumstances Under Which a Process is Swapped Out


A process is swapped out in the following cases:
Memory Shortage:
1. When there isn't enough memory to accommodate new or high-priority
processes.

Low-Priority Process:
1. Lower-priority processes are swapped out to allocate resources to more
critical ones.

Idle Process:
1. Processes waiting for I/O operations may be swapped out to free
memory.

System Load Management:


1. To improve system performance by balancing memory allocation
among processes.

A) II) Structure of Buffer Pool


A buffer pool is a collection of memory blocks used for temporary storage during I/O
operations.
Components of Buffer Pool
Free Buffers:
1. Buffers available for use.

Allocated Buffers:
1. Buffers currently being used by processes.

Buffer Headers:
1. Metadata associated with each buffer, including status and device
details.
Diagram
+-----------------+ +-----------------+
| Buffer Header 1 | -----> | Data Block 1 |
+-----------------+ +-----------------+
| Buffer Header 2 | -----> | Data Block 2 |
+-----------------+ +-----------------+
| ... | | ... |
+-----------------+ +-----------------+

B) UNIX System Architecture


The architecture of the UNIX operating system consists of several layers:
Diagram
+---------------------+
| User Applications |
+---------------------+
| Shell (CLI/GUI) |
+---------------------+
| Kernel |
| - Process Control |
| - Memory Management |
| - File System |
| - Device Drivers |
+---------------------+
| Hardware Layer |
+---------------------+
Explanation
User Applications:
1. Programs or processes run by the user, such as editors, compilers, etc.

Shell:
1. Interface between the user and the kernel; accepts commands and
executes them.
Kernel:
1. Core of the operating system; manages resources and handles system
calls.
2. Components:
1. Process Control: Manages processes (creation, scheduling).
2. Memory Management: Allocates memory dynamically to
processes.
3. File System: Manages files and directories.
4. Device Drivers: Interfaces with hardware devices.

Hardware Layer:
1. Includes physical devices such as CPU, memory, and I/O devices.
This layered approach ensures modularity and simplicity in UNIX system design.

Q7.Solve
A) I) Short Note on Process Context
A process context refers to all the information about a process required for its
execution by the operating system.
Components of Process Context
CPU Context:
1. The state of CPU registers, such as the program counter, stack pointer,
and general-purpose registers.

Memory Context:
1. Information about the process's memory, including page tables, virtual
address space, and segment mappings.

I/O Context:
1. Details about open files, sockets, and other I/O devices used by the
process.

Process Control Information:


1. Process ID (PID), parent PID (PPID), priority, and scheduling
information.
Importance of Process Context
 Enables process switching (context switching).
 Preserves the state of a process so it can resume execution from where it was
paused.

A) II) C Program to Suspend and Resume Process Using Signals


#include <stdio.h>
#include <signal.h>
#include <unistd.h>

void signal_handler(int signal) {


if (signal == SIGTSTP)
printf("Process Suspended.\n");
else if (signal == SIGCONT)
printf("Process Resumed.\n");
}

int main() {
signal(SIGTSTP, signal_handler); // Handle suspension
signal(SIGCONT, signal_handler); // Handle resumption

while (1) {
printf("Running process...\n");
sleep(2);
}
return 0;
}
Explanation
1. SIGTSTP: Suspends the process (usually triggered by Ctrl+Z).
2. SIGCONT: Resumes the process.
3. The program prints messages based on the signal received.
B) Anonymous Mapping and Its Advantages
What is Anonymous Mapping?
 Anonymous mapping is a memory allocation mechanism where memory is
mapped without an associated file.
 It is used for temporary data storage during program execution.
 Implemented using the mmap system call with the flag MAP_ANONYMOUS.
Advantages of Allocating Memory via Anonymous Mapping
No File Dependency:
o Memory is not tied to any file, reducing overhead and complexity.

Temporary Storage:
o Ideal for storing temporary data that doesn't need to be saved to a file.

Efficient Memory Use:


o Memory is allocated on demand and released when no longer needed.

Security:
o Since the data is not linked to a file, it reduces the risk of file-based
vulnerabilities.

Flexible Allocation:
o Supports dynamic allocation and resizing of memory.

Example Usage in C
#include <sys/mman.h>
#include <stdio.h>
#include <string.h>

int main() {
char *mem = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (mem == MAP_FAILED) {
perror("mmap failed");
return 1;
}

strcpy(mem, "Hello, Anonymous Memory!");


printf("%s\n", mem);

munmap(mem, 4096); // Release memory


return 0;
}
Advanced Operating System
Question Paper 2

Q1. Solve
A) Define Interrupt
An interrupt is a signal sent to the processor to indicate that a specific event needs
immediate attention. It temporarily halts the current execution of a program to execute
an interrupt service routine (ISR) and then resumes.

B) Differentiate Named and Unnamed Pipe


Aspect Named Pipe Unnamed Pipe
Identifier Has a specific name (file in filesystem). Does not have a name.
Allows communication between unrelated Limited to parent-child
Scope
processes. processes.
Exists only during process
Persistence Persistent until explicitly deleted.
execution.
Created using pipe() system
Creation Created using mkfifo() or mknod().
call.

C) Content of Buffer Header


1. Device Information: Identifies the device associated with the buffer.
2. Block Number: Indicates which block of the device is in the buffer.
3. Status Flags: Shows the buffer's state (e.g., locked, dirty, etc.).
4. Pointer to Data: Points to the actual data in the buffer.
5. Pointers for Linked List: Links to other buffer headers for management.

D) What is Signal? Features of Signal


A signal is a notification sent to a process by the operating system or another process
to inform it of an event.
Features of Signals
1. Asynchronous: Delivered asynchronously to processes.
2. Predefined: Signals like SIGKILL, SIGINT are predefined.
3. Signal Handlers: Processes can define custom actions for signals.
4. Interrupt Execution: Can interrupt running processes.

E) Justify: "In Linux, files are usually accessed via filenames."


1. Filenames as Identifiers: Linux uses filenames to uniquely identify files
within directories.
2. File System Hierarchy: Files are organized in a tree-like structure, making
filenames essential for navigation.
3. Abstraction: User-level programs interact with files using names, not device
addresses.
4. Ease of Use: Filenames are user-friendly compared to other identifiers like
inodes.

F) What is Hard Link?


A hard link is a direct reference to the inode of a file.
 Features:
1. Allows multiple names for the same file.
2. Changes to one hard link reflect in all others.
3. Deleting a hard link does not delete the file unless all links are
removed.

Q2.Solve

A) I) State and Explain setjmp() and longjmp() Functions


setjmp():
 Definition: Saves the current state of the program (stack context) in a buffer
for later use.
 Purpose: Used to mark a return point in the program if an error occurs.
 Syntax:
int setjmp(jmp_buf env);

 Return Value:
o Returns 0 when called initially.
o Returns the value passed by longjmp() during the jump.
longjmp():
 Definition: Restores the saved state using the buffer from setjmp().
 Purpose: Used to jump back to the point saved by setjmp().
 Syntax:
void longjmp(jmp_buf env, int val);

 Behavior:
o Transfers control back to the location of setjmp().
o Returns the value val to the program.

A) II) What Is an Orphan Process?


An orphan process is a child process whose parent process has terminated.
Sequence of Events for a Process to Become Orphan:
1. Parent Process Terminates: The parent process ends or crashes.
2. Child Process Continues: The child process remains running independently.
3. Adopted by Init/Systemd: In UNIX/Linux, the init or systemd process adopts
orphan processes to ensure proper handling.

B) Demand Paging Memory Management Mechanism


Definition:
Demand paging loads pages into memory only when they are required, reducing
memory usage.
Mechanism:
1. Page Table:
o Maps virtual addresses to physical frames.
o Includes a valid/invalid bit to indicate if the page is in memory.
2. Page Fault:
o Triggered when a program accesses a page not in memory.
o OS loads the required page from disk into memory.
3. Frame Allocation:
o Free memory frames are allocated to the requested pages.
4. Replacement Policy:
o When memory is full, page replacement algorithms (e.g., LRU, FIFO)
are used to evict pages.
Data Structures Used:
1. Page Table: Tracks the mapping between virtual pages and physical frames.
2. Frame Table: Records information about allocated physical memory frames.
3. Swap Space: Temporary storage on disk for pages swapped out of memory.
Advantages:
 Efficient memory usage.
 Only necessary pages are loaded, reducing overhead.
Diagram:
Virtual Memory --> Page Table --> Physical Memory
--> Swap Space (for evicted pages)

Q3. Solve

A) I) How Does the Command mkdir Work?


The mkdir (make directory) command is used to create a new directory in the file
system.
Working Steps:
1. Parse Input:
1. The command takes the directory name (and path) as input.
2. Example: mkdir myfolder.
2. System Call:
1. Internally, the mkdir command invokes the mkdir() system call to
create the directory.
2. Syntax: int mkdir(const char *pathname, mode_t mode);.
3. Check Permissions:
1. The OS checks if the user has write permissions in the parent directory.
4. Create Directory:
1. A new directory entry is created in the parent directory's metadata.
2. The new directory is initialized with . (current directory) and .. (parent
directory) entries.
5. Set Attributes:
1. Assigns the specified mode (permissions) and ownership to the new
directory.

A) II) Behavior of the Given C Program


Code Overview:
 The program uses a FIFO (named pipe) to communicate between processes.
 Depending on the number of arguments (argc), it writes to or reads from the
FIFO.
Program Execution:
1. Creation of FIFO:
o mknod("fifo", 010777, 0) creates a named pipe called fifo with
read/write permissions.
2. Argument Check:
o If argc == 2, the program opens the FIFO for writing and writes "hello"
in an infinite loop.
o If argc != 2, the program opens the FIFO for reading and reads from it
in an infinite loop.
3. Communication:
o When one instance of the program writes to the FIFO, another instance
(running separately) can read the data.
Behavior:
 This code demonstrates inter-process communication using a FIFO.
 The output depends on whether the program is run with or without an
argument:
o With an argument: Writes "hello" repeatedly to the FIFO.
o Without an argument: Reads data from the FIFO and stores it in buf.

B) Explain the Scenario of “Delayed Write Buffer” with Suitable Diagram


Delayed Write Buffer:
A mechanism in which changes to disk data are first written to a buffer in memory
and later written to the disk.
Scenario:
1. Write Request:
o When a process requests a write operation, the data is first written to
the buffer.
o This improves performance by avoiding immediate disk I/O.
2. Buffer Pool:
o The OS maintains a pool of buffers to store disk data temporarily.
3. Delayed Write:
o The actual write to the disk is deferred until:
 The buffer is needed for new data.
 A sync operation (e.g., fsync) is explicitly called.
 Periodic flushing occurs.
4. Advantages:
o Reduces frequent disk access.
o Optimizes I/O operations by combining multiple writes.
Diagram:
+----------------------+ +--------------------+
| Process Issues | Write Data | Buffer Pool |
| Write Request | -----------> | (In Memory) |
+----------------------+ +--------------------+
| |
| Flush to Disk (Delayed) |
v v
+----------------------+ +--------------------+
| Disk Storage | | Background Flush |
+----------------------+ +--------------------+
Example:
If a file is modified and the system crashes before the buffer is flushed to disk, the
changes might be lost. The use of delayed write requires mechanisms like journaling
to ensure data consistency.

Q4.Solve
A) I) Explain getcwd() System Call with Example
Explanation of getcwd():
 The getcwd() system call is used to get the current working directory (CWD)
of the calling process.
 It returns the absolute pathname of the current directory in which the process
is running.
 Syntax:
char* getcwd(char *buf, size_t size);

o buf: A pointer to a buffer where the current directory path will be
stored.
o size: The size of the buffer buf.
 If the buffer is large enough to hold the path, getcwd() stores the path in buf
and returns the pointer to buf. If the buffer is not large enough, it returns
NULL and sets errno.
Example:
#include <stdio.h>
#include <unistd.h>

int main() {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working directory: %s\n", cwd);
} else {
perror("getcwd() error");
}
return 0;
}
Output (Example):
Current working directory: /home/user

A) II) Write Short Note on dup() and dup2() System Calls


dup() System Call:
 The dup() system call duplicates an existing file descriptor and returns a new
file descriptor that refers to the same file or resource.
 Syntax:
int dup(int oldfd);

o oldfd: The file descriptor to duplicate.
o Returns: A new file descriptor, or -1 if an error occurs.
 The new file descriptor returned is the lowest available integer value that is
not already used.
 Both the original and the new file descriptor refer to the same open file, so
changes like file offset are shared between them.

dup2() System Call:


 The dup2() system call is similar to dup(), but it allows the user to specify the
new file descriptor.
 Syntax:
int dup2(int oldfd, int newfd);

ooldfd: The file descriptor to duplicate.
onewfd: The desired file descriptor to be assigned to the duplicate.
oIf newfd is already open, it is closed before being reused.
 If newfd is the same as oldfd, dup2() has no effect.
 It provides more control by allowing the user to specify the exact file
descriptor to be used.
Example:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main() {
int oldfd, newfd;
oldfd = open("example.txt", O_RDONLY);
if (oldfd < 0) {
perror("Failed to open file");
return 1;
}
newfd = dup2(oldfd, 10); // Duplicate to file descriptor 10
if (newfd < 0) {
perror("Failed to duplicate file descriptor");
return 1;
}

printf("File descriptor %d duplicated to %d\n", oldfd, newfd);


close(oldfd);
close(newfd);
return 0;
}

B) Explain Advantages & Disadvantages of mmap()


mmap() System Call:
The mmap() system call is used for memory-mapped file I/O. It maps files or devices
into memory, allowing programs to access them as if they were part of the process's
memory space.
Syntax:
void* mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset);
 addr: Desired starting address for the mapping (use NULL to let the system
choose).
 length: Length of the memory to map.
 prot: Memory protection options (e.g., PROT_READ, PROT_WRITE).
 flags: Mapping type (e.g., MAP_SHARED, MAP_PRIVATE).
 fd: File descriptor for the file to map.
 offset: Offset in the file to start the mapping.
Advantages of mmap():
1. Efficient Memory Access:
o Direct memory access to the contents of a file is possible, making I/O
faster as the data is mapped into the process's address space.
2. No Buffering:
o With mmap(), there is no need for explicit buffering (like with
read()/write()). Data is read and written directly in memory.
3. Shared Memory:
o When mapping a file with MAP_SHARED, changes made in the
memory area can be reflected back to the file, making it suitable for
shared memory usage.
4. Simplifies File Access:
o The process can treat file contents as if they are part of the memory,
simplifying the file handling in code.
Disadvantages of mmap():
1. Complexity in Error Handling:
o Errors like segmentation faults can occur when accessing memory
outside the mapped range, which is harder to handle compared to
traditional I/O functions.
2. Limited Portability:
o Not all systems support the full functionality of mmap(), especially
older or embedded systems.
3. Memory Overhead:
o The mmap() function may result in high memory consumption,
especially when mapping large files. The whole file might be loaded
into memory, leading to inefficiency in case of large files.
4. Requires File Descriptors:
o mmap() needs an open file descriptor, so it can’t be used without
having an existing file open, and this may cause resource management
issues.
Example:
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("open failed");
return 1;
}

// Memory-map the file


char *mapped = mmap(NULL, 1024, PROT_READ, MAP_SHARED, fd, 0);
if (mapped == MAP_FAILED) {
perror("mmap failed");
close(fd);
return 1;
}

// Access the mapped data


printf("File contents: %s\n", mapped);

// Unmap the file


munmap(mapped, 1024);
close(fd);
return 0;
}

Q5. Solve
A) I) Explain Process and Its State with Help of Diagram
Process:
 A process is a program in execution. It is an active entity that requires
resources such as CPU time, memory, and I/O devices to complete its task.
 A process goes through several states during its life cycle, which are as
follows:
Process States:
1. New:
o The process is being created.
2. Ready:
o The process is loaded into memory and is waiting for CPU time to be
assigned to it.
3. Running:
o The process is currently being executed by the CPU.
4. Blocked (or Waiting):
o The process is waiting for some event or resource (e.g., I/O
completion).
5. Terminated:
o The process has finished execution and is terminated.

State Transition Diagram:


+--------+ CPU +--------+
| | <-------------> | |
| New | Ready Queue | Ready |
| | | |
+--------+ +--------+
| |
| Process is | Process is
| created and | assigned
| moved to Ready | CPU time
| state | and moves
v v
+---------+ +---------+
| Running | <-------> | Blocked |
+---------+ +---------+
| |
| Process | Process waits
| finishes execution | for event (I/O)
v v
+---------+ +---------+
| Terminate| | Blocked|
+---------+ +---------+

A) II) Write a Program that Will Read Data from One File and Copy It to
Another File
C Program Example:
#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *source, *destination;
char ch;

// Open source file in read mode


source = fopen("source.txt", "r");
if (source == NULL) {
printf("Source file not found.\n");
exit(1);
}

// Open destination file in write mode


destination = fopen("destination.txt", "w");
if (destination == NULL) {
printf("Unable to open destination file.\n");
exit(1);
}

// Read and write data character by character


while ((ch = fgetc(source)) != EOF) {
fputc(ch, destination);
}

printf("File copied successfully.\n");

// Close both files


fclose(source);
fclose(destination);

return 0;
}
 This program copies data from source.txt to destination.txt character by
character. It handles both file opening and error cases properly.

B) What is Race Condition? Explain Any One Scenario in Which Race


Condition Occurs
Race Condition:
 A race condition occurs when two or more processes or threads access shared
resources (such as variables, files, etc.) concurrently and the final outcome
depends on the non-deterministic order in which the processes access the
shared resource.
 If proper synchronization mechanisms (e.g., locks or semaphores) are not
used, the outcome can be unpredictable and may lead to bugs or incorrect
behavior.
Example of Race Condition:
Consider a scenario where two processes are updating the same bank account balance
simultaneously without proper synchronization.
1. Initial Account Balance: $1000.
2. Process A tries to withdraw $200.
3. Process B tries to withdraw $300.
4. If Process A and Process B read the balance at the same time before updating
it (without synchronization), both may think the balance is still $1000 and
proceed to deduct $200 and $300, respectively.
5. This would result in the account balance becoming $500 instead of $700
(which is the correct balance after both withdrawals).
This is a classic example of a race condition because the final result depends on the
order in which the processes execute. Proper synchronization (e.g., using mutexes) is
required to prevent this problem.

Q6.Solve

A) I) Write Program to Demonstrate the Use of calloc(), free() System Calls


Program Example:
#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;
int size, i;

// Asking the user for the number of elements


printf("Enter the number of elements: ");
scanf("%d", &size);

// Using calloc to allocate memory


ptr = (int *)calloc(size, sizeof(int));
// Check if memory allocation was successful
if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

// Assigning values to the allocated memory


for (i = 0; i < size; i++) {
ptr[i] = i * 10; // Assigning multiples of 10
}

// Printing the allocated memory values


printf("The allocated memory contains:\n");
for (i = 0; i < size; i++) {
printf("%d ", ptr[i]);
}
printf("\n");

// Using free to deallocate memory


free(ptr);
printf("Memory deallocated.\n");

return 0;
}

Explanation:
 calloc(): Allocates memory for a specified number of elements, initialized to
zero. In this example, it allocates memory for size number of integers and
initializes them to 0.
 free(): Deallocates previously allocated memory. In this example, memory
allocated using calloc() is freed using free().

A) II) Write a Short Note on Swapping Concept


Swapping:
Swapping is a memory management technique in which a process is moved
from main memory (RAM) to secondary memory (e.g., hard disk) to free up
space for other processes.
It involves:
1. Swapping Out: A process is temporarily moved from RAM to disk
(swap space) when the system is low on memory or when it's not
actively being used.
2. Swapping In: The process is brought back into RAM when needed.
Purpose: Swapping helps in improving system performance by enabling
multiple processes to run even when the system has limited physical memory.
It allows better utilization of system resources.
Drawback: Frequent swapping may degrade system performance, as it
involves disk I/O operations, which are much slower than memory operations.

B) Define the Following Concepts


I) Fork:
 fork() is a system call used to create a new process by duplicating the calling
(parent) process. The new process is called the child process.
 After fork(), both parent and child processes continue executing from the point
where the fork() was called.
 Syntax:
pid_t fork(void);
 It returns:
o 0 to the child process
o A positive integer (PID of the child) to the parent process.
II) Pipe:
 Pipe is a method of inter-process communication (IPC) that allows one
process to send its output (standard output) to another process as input
(standard input).
 Pipes are unidirectional; data flows in one direction from one process to
another.
 There are two types:
o Unnamed Pipe: Used for communication between related processes
(e.g., parent and child).
o Named Pipe (FIFO): Allows communication between unrelated
processes.

III) Shell:
 A shell is a command-line interface (CLI) that allows users to interact with the
operating system by typing commands. It interprets user commands and passes
them to the kernel.
 Examples of shells include Bash, Zsh, and Tcsh.
 Shells can execute scripts, handle environment variables, and manage user
input.
IV) Inode:
 An inode (Index Node) is a data structure used by file systems to store
information about a file or directory, excluding the actual data.
 It contains metadata about a file, such as its size, ownership (user/group),
permissions, timestamps, and location of the data blocks on the disk.
 Each file in a filesystem has an inode.
V) Super Block:
 The superblock is a data structure in a file system that contains information
about the file system itself, such as its size, block size, free space, and
information about the file system's structure.
 It is stored at the beginning of the file system and is essential for the
functioning of the file system.

Q7. Solve

A) I) Explain the Architecture of Unix OS


The architecture of Unix OS is structured in layers, each responsible for a specific
function. It can be explained as follows:
Kernel:
1. The core part of the Unix operating system, managing hardware
resources, system processes, and memory management.
2. It provides services like process scheduling, system calls, I/O
operations, and security.
3. It interacts with the hardware directly and controls the execution of
processes.

Shell:
1. The command-line interface between the user and the kernel.
2. It takes user commands, processes them, and calls the kernel for
execution.
3. Examples include Bash and Csh (C Shell).

File System:
1. Responsible for organizing and storing files on the system.
2. It manages directories, files, and permissions.
3. The file system is hierarchical, with directories and subdirectories.

System Utilities:
1. These are system programs that perform tasks such as file
manipulation, text processing, etc.
2. Examples include tools like grep, awk, sed, and more.

User Programs:
1. Applications and utilities that users run on top of Unix.
2. They can range from text editors to web browsers to more specialized
software.
Diagram of Unix Architecture:
------------------------------------------------------
| User Level |
------------------------------------------------------
| Shell / User Programs |
------------------------------------------------------
| System Utilities |
------------------------------------------------------
| Kernel Level |
------------------------------------------------------
| File System | Memory Management | I/O |
------------------------------------------------------
| Hardware (Physical Devices) |
------------------------------------------------------

A) II) What is Data Segment? How to Manage It


Data Segment:
 The data segment is a portion of memory where global variables and static
variables are stored during the program's execution.
 It is divided into two parts:
1. Initialized Data Segment: Contains variables that are explicitly
initialized in the code.
2. Uninitialized Data Segment (BSS): Contains variables that are
declared but not initialized by the programmer.
Managing the Data Segment:
 The operating system allocates memory to the data segment when a program is
loaded into memory.
 The compiler generates the necessary code to store values in the data segment.
 Memory management techniques like paging and segmentation are used to
manage and protect the data segment.

B) Write a C Program to Handle Two-Way Communication Between Parent &


Child Using Pipe
C Program Example:
This program demonstrates two-way communication between a parent and child
process using two pipes:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
int pipe1[2], pipe2[2];
pid_t pid;
char write_msg[] = "Hello, Child!";
char read_msg[100];
// Creating two pipes
if (pipe(pipe1) == -1) {
perror("Pipe1 failed");
exit(1);
}
if (pipe(pipe2) == -1) {
perror("Pipe2 failed");
exit(1);
}

// Creating a child process using fork


pid = fork();

if (pid == -1) {
perror("Fork failed");
exit(1);
}

if (pid == 0) { // Child Process


// Close the write end of pipe1 and read end of pipe2
close(pipe1[1]);
close(pipe2[0]);

// Read from pipe1


read(pipe1[0], read_msg, sizeof(read_msg));
printf("Child received: %s\n", read_msg);

// Send a response to the parent


write(pipe2[1], "Hello, Parent!", 15);

close(pipe1[0]);
close(pipe2[1]);
} else { // Parent Process
// Close the read end of pipe1 and write end of pipe2
close(pipe1[0]);
close(pipe2[1]);

// Send message to child


write(pipe1[1], write_msg, sizeof(write_msg));

// Read the response from child


read(pipe2[0], read_msg, sizeof(read_msg));
printf("Parent received: %s\n", read_msg);
close(pipe1[1]);
close(pipe2[0]);
}

return 0;
}
Explanation:
 Pipe Creation: Two pipes are created using pipe(). The first pipe (pipe1) is
used for communication from parent to child, and the second pipe (pipe2) is
used for communication from child to parent.
 Forking: The fork() system call is used to create a child process.
 Parent Process: The parent writes a message to the child through pipe1 and
reads a response from the child through pipe2.
 Child Process: The child reads the message from the parent through pipe1 and
writes a response to the parent through pipe2.
 Two-Way Communication: Both processes communicate through the pipes
in a bidirectional manner.

You might also like