0% found this document useful (0 votes)
79 views20 pages

AOS Question Paper Previous y

The document contains a series of questions and answers related to operating systems, covering topics such as the kernel, process management, system calls, and inter-process communication. Key concepts include the behavior of the fork() system call, the structure of regular files, and the use of pipes for IPC. Additionally, it provides example C programs demonstrating various functionalities like reading commands and handling signals.

Uploaded by

yash mandhare
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)
79 views20 pages

AOS Question Paper Previous y

The document contains a series of questions and answers related to operating systems, covering topics such as the kernel, process management, system calls, and inter-process communication. Key concepts include the behavior of the fork() system call, the structure of regular files, and the use of pipes for IPC. Additionally, it provides example C programs demonstrating various functionalities like reading commands and handling signals.

Uploaded by

yash mandhare
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/ 20

AOS Question paper

Q-a) True or False? Justify:


"The kernel is a separate set of processes that run in parallel to user processes."

Ans-a)
False.
The kernel is not a separate set of processes running in parallel to user processes. Instead, it is the
core part of the operating system that manages hardware resources and system calls. It executes in
privileged mode and is responsible for tasks like process management, memory management, and
device control. The kernel operates in the background and does not act as separate processes.

Q-b) What are the 4 different conditions for the pid argument of the kill system call?

Ans-b)
The pid argument in the kill system call can have the following conditions:

1. Positive PID: The signal is sent to the process with the given PID.

2. Zero PID: The signal is sent to all processes in the same process group as the caller.

3. Negative PID: The signal is sent to all processes in the process group specified by the
absolute value of pid.

4. -1 PID: The signal is sent to all processes for which the caller has permission, excluding
special system processes.

Q-c) What is the difference between wait and waitpid?

Ans-c)

1. wait:

o Waits for any child process to terminate.

o Does not provide control over which specific child process is waited on.

o Syntax: pid_t wait(int *status);

2. waitpid:

o Waits for a specific child process or a set of child processes to terminate based on
the PID.

o Provides more control over process management.

o Syntax: pid_t waitpid(pid_t pid, int *status, int options);

Q-d) If we execute lseek(fd, 0, 2), then what will be the new file byte offset?
Ans-d)
lseek(fd, 0, 2) sets the file offset to the end of the file (SEEK_END).

 The new file byte offset will be equal to the size of the file in bytes.

Q-e)

What is a broken link?

Ans-e)
A broken link (also known as a dangling symbolic link) occurs when a symbolic link points to a target
file or directory that no longer exists or has been moved. This makes the link unusable.

Q-f)

How to obtain the process ID and parent process ID?

Ans-f)

1. Process ID (PID): Use the getpid() system call.

o Example: pid_t pid = getpid();

2. Parent Process ID (PPID): Use the getppid() system call.

o Example: pid_t ppid = getppid();

Q-g)

What is the output of the following code?

#include<stdio.h>

#include<unistd.h>

int main() {

if (fork() && (!fork())) {

if (fork() || fork()) {

fork();

printf("2");

return 0;

}
Ans-g)
Let's analyze the code step by step:

1. The first fork() creates one child process, making two processes in total.

2. The parent process proceeds to check the condition (fork() && (!fork())). Depending on the
evaluation, additional processes are created.

3. The nested fork() calls further multiply the number of processes.

Total Processes: The number of processes created and their order of execution depend on how the
fork() calls are evaluated. Since there are multiple nested fork() calls, a total of 10 processes will
execute the printf("2"); statement.

Output: The output will be "2222222222" (ten times "2" printed by each process).

Q2-a-i)

What is a process? Draw and explain the state transition diagram of a process.

Ans-a-i)
A process is an instance of a program in execution. It includes program code, current activity, and
associated resources like memory, files, and CPU time. Processes are the fundamental units of work
in an operating system.

State Transition Diagram of a Process:

States Explanation:

1. New: The process is created but has not yet been admitted into the ready queue.

2. Ready: The process is ready to run but is waiting for CPU allocation.

3. Running: The process is currently being executed by the CPU.

4. Waiting: The process is waiting for an event (e.g., I/O completion).

5. Terminated: The process has completed its execution.

Transitions:

1. New → Ready: After process creation.

2. Ready → Running: When the process is selected by the CPU scheduler.

3. Running → Waiting: When the process waits for I/O or an event.

4. Running → Terminated: When the process completes its execution.

5. Waiting → Ready: When the waiting event is completed.

6. Running → Ready: When the CPU is preempted or a higher-priority process needs the CPU.
Q2-a-ii)

Explain any three data structures for Demand Paging.

Ans-a-ii)

1. Page Table:

o Maps virtual memory addresses to physical memory frames.

o Tracks if a page is in memory or needs to be fetched from disk.

2. Swap Space Management:

o Holds pages that are not currently in main memory.

o Allows efficient retrieval and storage of pages.

3. Frame Table:

o Tracks all physical memory frames.

o Maintains information about which process and page is using each frame.

Q2-b)

Explain the syntax of the following system calls.

Ans-b)

1. alarm()

o Syntax: unsigned int alarm(unsigned int seconds);

o Description: Schedules a SIGALRM signal to be sent to the process after the specified
time in seconds.

2. kill()

o Syntax: int kill(pid_t pid, int sig);

o Description: Sends a signal (sig) to a process or a group of processes identified by


pid.

3. sbrk()

o Syntax: void *sbrk(intptr_t increment);

o Description: Adjusts the program’s data segment size by increment bytes. Returns a
pointer to the new program break.

4. execl()

o Syntax: int execl(const char *path, const char *arg, ..., NULL);

o Description: Replaces the current process image with a new process image specified
by path and arguments.
5. fchmod()

o Syntax: int fchmod(int fd, mode_t mode);

o Description: Changes the permissions of a file referred to by the file descriptor fd to


the specified mode.

Q3-a-i)

Explain the fourth scenario for buffer allocation.

Ans-a-i)
The fourth scenario for buffer allocation refers to a situation where both the process requesting the
buffer and the process holding the buffer are of the same priority. In such cases, the allocation
system resolves the deadlock by preempting the buffer from the holding process. This is done to
ensure system efficiency and fairness.

 The buffer is forcibly reclaimed and allocated to the requesting process.

 A mechanism must exist to avoid indefinite starvation of the process whose buffer was
preempted.

 This scenario requires careful handling to prevent further deadlocks.

Q3-a-ii)

Explain the behavior of the following C program.

#include<fcntl.h>

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

int fd, skval;

char c;

if(argc != 2)

exit();

while(skval = read(fd, &c, 1)) {

printf(“char%c\n”, c);

skval = lseek(fd, 1023L, 1);

printf(“new seek val%d\n”, skval);

}
Ans-a-ii)
Behavior of the program:

1. Purpose:
The program attempts to read characters from a file and seeks forward by 1023 bytes after
every read operation.

2. Issues in the program:

o File Descriptor Initialization: The file descriptor fd is not initialized with a valid file
(missing fd = open(argv[1], O_RDONLY);).

o Exit Issue: The exit() call is missing a proper argument, which should ideally be
exit(1);.

3. Expected Behavior:

o If corrected, the program will read one character from the file, print it, then jump
1023 bytes forward using lseek(fd, 1023L, 1), and print the new seek position.

o This process repeats until the end of the file is reached.

Output Example:
If fixed, the output will look like this (assuming a valid file):

char a

new seek val 1024

char b

new seek val 2048

...

Q3-b)

Write a C program to print the type of file for each command-line argument.

Ans-b)
Here is a C program to print the type of file for each command-line argument:

#include <stdio.h>

#include <sys/stat.h>

#include <stdlib.h>

void print_file_type(const char *path) {

struct stat fileStat;

if (stat(path, &fileStat) < 0) {

perror("stat");
return;

printf("File: %s - Type: ", path);

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/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\n");

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

if (argc < 2) {

printf("Usage: %s <file1> <file2> ...\n", argv[0]);

exit(1);

for (int i = 1; i < argc; i++) {

print_file_type(argv[i]);

return 0;

}
Explanation:

1. The program uses stat() to retrieve information about the file.

2. The file type is determined using macros like S_ISREG, S_ISDIR, etc.

3. Each command-line argument is processed, and the file type is printed.

Example Output:
Command:

./filetype a.txt /home /dev/null

Output:

File: a.txt - Type: Regular File

File: /home - Type: Directory

File: /dev/null - Type: Character Device

Q4-a-i)

What are pipes? Explain named pipes and unnamed pipes.

Ans-a-i)
Pipes are inter-process communication (IPC) mechanisms that allow data to be transferred
unidirectionally between two processes. They act like a buffer, enabling one process to write data
and another to read it.

Types of Pipes:

1. Unnamed Pipes:

o Used for communication between related processes (e.g., parent and child
processes).

o Created using the pipe() system call.

o Data flows in one direction, and both processes must share the pipe file descriptor.

Example:

int pipefd[2];

pipe(pipefd); // Creates an unnamed pipe

2. Named Pipes (FIFOs):

o Allow communication between unrelated processes.

o Created using the mkfifo() system call.

o Appear as a file in the filesystem, enabling processes to open, read, and write using
standard file operations.
Example:

mkfifo("myfifo", 0666); // Creates a named pipe

Q4-a-ii)

Which operations are performed by the kernel during execution of fork()?

Ans-a-ii)
When fork() is executed, the kernel performs the following operations:

1. Process Duplication:

o Creates a new process (child) that is an exact copy of the parent process.

2. Copy-on-Write Memory:

o Memory pages of the parent are shared with the child initially. Separate copies are
created only when one process modifies the memory (copy-on-write mechanism).

3. Resource Duplication:

o Copies file descriptors, signal handlers, and process state.

o File descriptors point to the same underlying files as the parent.

4. Unique Process ID:

o Assigns a unique PID to the child process.

5. Execution State:

o The return value of fork() is different in parent and child processes:

 Parent receives the child PID.

 Child receives 0.

Q4-b)

Write a C program to demonstrate race condition in catching signals.

Ans-b)
Here is a program that demonstrates a race condition when catching signals:

#include <stdio.h>

#include <stdlib.h>

#include <signal.h>

#include <unistd.h>

int counter = 0;
void signal_handler(int sig) {

counter++; // Critical section, not protected

printf("Signal caught: %d, Counter: %d\n", sig, counter);

int main() {

signal(SIGUSR1, signal_handler);

pid_t pid = fork();

if (pid == 0) {

// Child process

for (int i = 0; i < 10; i++) {

kill(getppid(), SIGUSR1); // Send signal to parent

usleep(100); // Slight delay

exit(0);

} else {

// Parent process

for (int i = 0; i < 10; i++) {

kill(getpid(), SIGUSR1); // Send signal to itself

usleep(100); // Slight delay

wait(NULL); // Wait for child to finish

printf("Final Counter Value: %d\n", counter);

return 0;

Explanation:

1. The program sets up a signal handler for SIGUSR1 that increments a global counter.
2. Both the parent and child processes send SIGUSR1 signals, resulting in multiple updates to
the counter in the signal handler.

3. Race Condition: The counter is accessed by both processes without synchronization, leading
to unpredictable final values.

Output Example (varies):

Signal caught: 10, Counter: 1

Signal caught: 10, Counter: 2

...

Final Counter Value: 12

Solution to Avoid Race Condition: Use synchronization mechanisms such as semaphores or mutexes
to protect the critical section.

Q5-a-i)

Under which circumstances is the process swapped out?

Ans-a-i)
A process is swapped out under the following circumstances:

1. Memory Shortage:

o When the system runs out of physical memory, inactive processes are swapped out
to free up space for active processes.

2. Process Priority:

o Low-priority processes may be swapped out to allocate resources to high-priority


processes.

3. I/O Waiting:

o A process waiting for I/O operations (disk, network, etc.) can be swapped out to
allow other processes to utilize the CPU.

4. System Load Balancing:

o During high system load, processes may be swapped out to maintain overall
performance and prevent overcommitment of resources.

5. Explicit Kernel Directive:

o The operating system may decide to swap out a process as part of memory
management policies, such as paging or swapping.
Q5-a-ii)

Explain the structure of a regular file with a suitable diagram.

Ans-a-ii)
The structure of a regular file in a Unix-like system consists of:

1. Inode:

o Contains metadata about the file, such as size, permissions, owner, and pointers to
data blocks.

2. Data Blocks:

o Store the actual content of the file.

3. Indirect Blocks:

o Used when the file size exceeds the capacity of direct pointers in the inode. These
include:

 Single Indirect Block: Points to a block that contains pointers to data blocks.

 Double Indirect Block: Points to a block that contains pointers to single


indirect blocks.

 Triple Indirect Block: Points to a block that contains pointers to double


indirect blocks.

Diagram:

Q5-b)

C program that creates a child process to read commands from the standard input and execute
them (no arguments passed).

Ans-b)
Here is a C program to create a child process that reads commands and executes them:

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <string.h>
int main() {

pid_t pid;

char command[100];

while (1) {

printf("Enter command to execute (or 'exit' to quit): ");

fgets(command, sizeof(command), stdin);

command[strcspn(command, "\n")] = '\0'; // Remove trailing newline

if (strcmp(command, "exit") == 0) {

printf("Exiting...\n");

break;

pid = fork();

if (pid < 0) {

perror("Fork failed");

exit(1);

} else if (pid == 0) {

// Child process: Execute the command

execlp(command, command, NULL);

perror("Execution failed");

exit(1);

} else {

// Parent process: Wait for child to complete

wait(NULL);

return 0;
}

Explanation:

1. Parent Process:

o Reads commands from the user.

o Creates a child process using fork().

2. Child Process:

o Executes the command using execlp().

o If execution fails, an error message is displayed.

3. Exit Command:

o If the user enters exit, the program terminates.

Example Output:

Enter command to execute (or 'exit' to quit): ls

<output of ls>

Enter command to execute (or 'exit' to quit): pwd

/home/user

Enter command to execute (or 'exit' to quit): exit

Exiting...

Q6-a-i)

Under which circumstances is the process swapped out?

Ans-a-i)
A process is swapped out under the following circumstances:

1. Memory Shortage:

o When physical memory is insufficient, inactive processes are swapped out to free
memory for active processes.

2. Process Priority:

o Lower-priority processes may be swapped out to provide resources to higher-priority


processes.

3. I/O Bound Processes:


o Processes waiting for I/O operations can be swapped out to allow CPU-bound
processes to execute.

4. System Overload:

o During high system load, swapping helps balance the load and ensure better
utilization of resources.

5. Explicit Kernel Decision:

o The operating system may decide to swap out processes based on its memory
management policies.

Q6-a-ii)

Draw and explain the structure of the buffer pool.

Ans-a-ii)
Buffer Pool Structure:

The buffer pool is a collection of buffers maintained in memory to manage disk I/O efficiently.

Components of Buffer Pool:

1. Buffer Headers:

o Contain metadata about each buffer, such as its status, reference count, and pointers
to data blocks.

2. Free List:

o A linked list of buffers that are currently free and can be allocated.

3. Hash Queue:

o Buffers are organized into hash queues based on the block number of the data they
hold. This allows quick lookup of buffers.

Diagram:

Explanation:

 Free Buffers: Buffers not currently used are part of the free list.

 In-Use Buffers: Buffers holding data from disk and currently accessed are linked via hash
queues for efficient access.

 When a process requests a block, the kernel searches the hash queue for the buffer or
allocates a free buffer if not found.
Q6-b)

Draw and explain the Unix System Architecture.

Ans-b)

Unix System Architecture:

The Unix system is divided into three main layers:

1. Hardware Layer:

o Includes physical devices like CPU, memory, and I/O devices.

o Provides the foundation for the operating system to interact with the hardware.

2. Kernel Layer:

o Core part of the operating system.

o Handles essential services like process management, memory management, file


systems, and device drivers.

3. User Layer:

o Includes shells, libraries, and application programs.

o Users interact with this layer using commands or programs.

Diagram:

Explanation:

1. Hardware: Provides resources for the operating system and applications.

2. Kernel:

o Acts as an intermediary between hardware and user applications.

o Implements core functionalities like scheduling, I/O control, and inter-process


communication.

3. User Applications:
o Users execute commands or run applications that interact with the kernel through
system calls.

Q7-a-i)

Write a short note on process context.

Ans-a-i)
Process context refers to the state and environment of a process at any given time, which allows it to
resume execution correctly after being interrupted or preempted. It includes all the information
needed by the operating system to manage and execute the process.

Components of Process Context:

1. User Context:

o Includes the user program's state, such as program counter (PC), stack pointer (SP),
and general-purpose registers.

2. Kernel Context:

o Includes kernel-mode registers, system call state, and kernel stack.

3. Address Space:

o The memory mapping of the process, including code, data, heap, and stack
segments.

4. Process-Specific Data:

o Information about file descriptors, signal handlers, and process priority.

The OS saves and restores the process context during context switching to ensure seamless execution
of processes.

Q7-a-ii)

Write a C program to illustrate suspending and resuming a process using signals.

Ans-a-ii)
Here is a C program demonstrating suspending and resuming a process using SIGSTOP and SIGCONT
signals:

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <signal.h>
void handle_signal(int sig) {

if (sig == SIGUSR1) {

printf("Received SIGUSR1: Suspending process...\n");

raise(SIGSTOP); // Suspend process

} else if (sig == SIGCONT) {

printf("Received SIGCONT: Resuming process...\n");

int main() {

signal(SIGUSR1, handle_signal); // Setup signal handler for SIGUSR1

signal(SIGCONT, handle_signal); // Setup signal handler for SIGCONT

printf("Process ID: %d\n", getpid());

printf("Send SIGUSR1 to suspend and SIGCONT to resume the process.\n");

while (1) {

printf("Process running...\n");

sleep(2);

return 0;

Explanation:

1. The program sets up signal handlers for SIGUSR1 (to suspend the process) and SIGCONT (to
resume it).

2. The process can be suspended using the kill -SIGUSR1 <pid> command and resumed using
kill -SIGCONT <pid>.

Output Example:

Process ID: 12345

Send SIGUSR1 to suspend and SIGCONT to resume the process.

Process running...
(After sending SIGUSR1)

Received SIGUSR1: Suspending process...

(After sending SIGCONT)

Received SIGCONT: Resuming process...

Q7-b)

What is anonymous memory mapping? What are the advantages of allocating memory via
anonymous memory mapping?

Ans-b)
Anonymous Memory Mapping:

 A mechanism where memory is allocated directly to a process without being backed by a file.

 The mmap() system call is used with the MAP_ANONYMOUS flag to allocate memory.

 The memory is initialized to zero and is only accessible to the process unless shared explicitly.

Advantages of Allocating Memory via Anonymous Memory Mapping:

1. Efficient Memory Allocation:

o No need to manage temporary files for storage, reducing I/O overhead.

2. Dynamic Allocation:

o Memory can be allocated and deallocated dynamically during runtime.

3. Memory Isolation:

o The memory is isolated to the process, enhancing security and reducing interference.

4. Custom Memory Management:

o Provides greater flexibility for applications that require specific memory alignment or
allocation patterns.

5. Shared Memory Support:

o When combined with MAP_SHARED, processes can share anonymous memory


segments, facilitating inter-process communication.

Example of Anonymous Mapping in C:

#include <sys/mman.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>
int main() {

size_t size = 4096; // Allocate 4 KB

void *ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1,


0);

if (ptr == MAP_FAILED) {

perror("mmap");

exit(1);

strcpy((char *)ptr, "Hello, Anonymous Memory!");

printf("%s\n", (char *)ptr);

munmap(ptr, size); // Free allocated memory

return 0;

You might also like