Advanced Operating System Solved Question Paper
Advanced Operating System Solved Question Paper
Question Paper 1
Q1.Solve
Q2.Solve
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
Advantages:
o Combines the strengths of fixed and dynamic allocation.
o Reduces fragmentation.
o Efficient memory usage for diverse workloads.
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
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.
int counter = 0;
int main() {
signal(SIGINT, signal_handler); // Handle Ctrl+C (SIGINT)
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.
int main() {
char command[100];
pid_t pid;
while (1) {
printf("Enter command to execute (or 'exit' to quit): ");
fgets(command, sizeof(command), stdin);
if (strcmp(command, "exit") == 0) {
break;
}
pid = fork();
return 0;
}
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
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.
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 |
+-----------------+ +-----------------+
| ... | | ... |
+-----------------+ +-----------------+
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.
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.
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;
}
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.
Q2.Solve
Q3. Solve
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
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;
}
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("open failed");
return 1;
}
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.
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;
return 0;
}
This program copies data from source.txt to destination.txt character by
character. It handles both file opening and error cases properly.
Q6.Solve
int main() {
int *ptr;
int size, i;
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().
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
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) |
------------------------------------------------------
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);
}
if (pid == -1) {
perror("Fork failed");
exit(1);
}
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]);
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.