0% found this document useful (0 votes)
4 views13 pages

System Programming

A system call is an interface for user-space programs to request services from the kernel, enabling safe access to privileged operations. System calls differ from library functions in execution space, privilege, and speed, with examples including read() and fork(). Understanding system calls is essential for managing processes, memory, and inter-process communication in operating systems.

Uploaded by

sinhaisshika
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)
4 views13 pages

System Programming

A system call is an interface for user-space programs to request services from the kernel, enabling safe access to privileged operations. System calls differ from library functions in execution space, privilege, and speed, with examples including read() and fork(). Understanding system calls is essential for managing processes, memory, and inter-process communication in operating systems.

Uploaded by

sinhaisshika
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

What is a System Call?

A system call is a controlled interface through which a user-space program requests a


service from the kernel.

In simple terms:

A system call is the mechanism that allows a user process to safely enter kernel mode
and request privileged operations.

Examples

read(), write()

fork(), exec()

Why Do We Need System Calls?

1. Protection and Security

User applications run in user mode, where they:

Cannot access hardware directly

Cannot access kernel memory

Cannot execute privileged CPU instructions

· · Difference between system call and library function?

Aspect System Call Library Function


Execution space Kernel space User space
Mode switch Yes No (unless it calls a syscall)
Privilege Privileged Non-privileged
Speed Slower Faster
Hardware access Yes No
Example read() printf()

How does a system call transition from user space to kernel space?

· User program calls a library function (e.g., read()).

· · The wrapper loads syscall number and arguments into registers.

· · A special instruction (SVC on ARM / syscall on x86) is executed.

· · CPU switches from user mode to kernel mode and runs the syscall handler.

Kernel completes the request and returns control to user space.


What happens internally when a process calls read()?

Same as previous.

· Explain fork(), vfork(), and clone() differences.

fork vfork
Creates child process with separate Creates child process with same address
virtual address space space of parent
Child and parent runs independently Parent is suspended, untill child calls
exec() or exit()
COPY-ON-WRITE is used No COPY-ON-WRITE

Copy-On-Write means:

Parent and child initially share the same physical memory pages, and a copy is made only
when one of them tries to modify the memory.

What does exec() do? Why doesn’t it return on success?

exec() replaces the current process with a new program, and it does not return on success
because the original process image is completely overwritten.

Difference between exit() and _exit()?

· exit(): Cleans up by flushing stdio buffers, calls atexit() handlers, then terminates the
process.

· _exit(): Immediately terminates the process without flushing stdio buffers or calling cleanup
handlers (used after fork() in the child).

What is a zombie process? How do you handle it?

A zombie process is a process that has finished execution (terminated) but still has an entry
in the process [Link] occurs because the parent process has not yet read the child’s exit
status using wait() or waitpid()

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <sys/wait.h>

int main() {

pid_t pid = fork();

if (pid < 0) {
perror("fork failed");

exit(1);

if (pid == 0) {

// Child process

printf("Child process running...\n");

sleep(2); // Simulate some work

printf("Child process exiting.\n");

exit(0); // Child terminates

} else {

// Parent process

int status;

printf("Parent waiting for child to terminate...\n");

// Wait for child to finish and reap it (avoids zombie)

wait(&status);

if (WIFEXITED(status)) {

printf("Child exited with status %d\n", WEXITSTATUS(status));

printf("Parent exiting.\n");

return 0;

What is an orphan process?

An orphan process is a process whose parent has terminated or exited before [Link] this
happens, the orphan process is adopted by the init process (PID 1) in Unix/Linux
[Link] init process becomes the new parent and is responsible for cleaning up when
the orphan process eventually terminates.

How does wait() / waitpid() work?

· · What is brk() / sbrk()? Are they still used?

· · Difference between malloc() and mmap()?

· · What is file descriptor? How does the kernel track it?

· · What is the maximum number of open file descriptors?

· · Difference between blocking and non-blocking I/O?

· · What is select() / poll() / epoll()?

1. Create a child process and execute ls -l

pid_t pid = fork();if (pid == 0) {

execl("/bin/ls", "ls", "-l", NULL);

perror("execl");

_exit(1);

} else {

wait(NULL);

Q2. Copy contents of one file to another using system calls

int fd1 = open("[Link]", O_RDONLY);int fd2 = open("[Link]", O_WRONLY | O_CREAT |


O_TRUNC, 0644);char buf[1024];ssize_t n;while ((n = read(fd1, buf, sizeof(buf))) > 0) {

write(fd2, buf, n);

close(fd1);

close(fd2);

Q3. Demonstrate dup() / dup2()

int fd = open("[Link]", O_WRONLY | O_CREAT, 0644);

dup2(fd, STDOUT_FILENO);printf("This goes to file\n");

What are different IPC mechanisms in Linux?


Pipes

FIFO

Shared Memory

Message Queue

Semaphores

Sockets

Difference between pipe and FIFO?

Anonymous pipe vs named pipe?

When would you use shared memory?

What problem do semaphores solve?

Difference between binary semaphore and mutex?

Why is shared memory fastest IPC?

What is race condition?

What is deadlock? Conditions for deadlock?

What is starvation?

Difference between POSIX and System V IPC?

Coding Questions (IPC)

Q1. Parent → Child communication using pipe

int fd[2];

pipe(fd);

if (fork() == 0) {

close(fd[1]);

char buf[100];

read(fd[0], buf, sizeof(buf));

printf("Child received: %s\n", buf);

} else {
close(fd[0]);

write(fd[1], "Hello", 6);

Q2. Shared memory example

int shmid = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0666);char *data =


shmat(shmid, NULL, 0);strcpy(data, "Shared Data");

Multi-Threading (POSIX Threads – MUST PREPARE DEEPLY)

Conceptual Questions

Difference between process and thread?

Why are threads faster than processes?

What resources are shared between threads?

What is thread stack?

What is race condition?

What is critical section?

What is mutex? How does it work internally?

Mutex vs semaphore?

What is deadlock in threads?

How do you avoid deadlock?

What is thread starvation?

What is priority inversion?

What is condition variable?

Spurious wakeup – what is it?

What happens if a thread exits without joining?

Coding Questions (Threads)

Q1. Create and join a thread

void* func(void* arg) {

printf("Thread running\n");
return NULL;

int main() {

pthread_t tid;

pthread_create(&tid, NULL, func, NULL);

pthread_join(tid, NULL);

Q2. Protect shared variable using mutex

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;int count = 0;

void* inc(void* arg) {

pthread_mutex_lock(&lock);

count++;

pthread_mutex_unlock(&lock);

return NULL;

Q3. Producer-Consumer using condition variables

pthread_mutex_t m;pthread_cond_t c;int ready = 0;

void* producer() {

pthread_mutex_lock(&m);

ready = 1;

pthread_cond_signal(&c);

pthread_mutex_unlock(&m);

4. systemd (Often Asked but Candidates Ignore)

Conceptual Questions

What is systemd?
Difference between systemd and init?

What is a unit file?

Types of systemd units?

service

target

socket

timer

What is systemctl?

What is a target?

How do you create a custom service?

Difference between ExecStart and ExecStartPre?

What is WantedBy=[Link]?

How does systemd manage dependencies?

How do you check service logs?

Practical systemd Questions

Q1. Create a simple service

[Unit]Description=My Test ServiceAfter=[Link]

[Service]ExecStart=/usr/bin/myappRestart=always

[Install]WantedBy=[Link]

Q2. Commands

systemctl daemon-reload

systemctl enable myservice

systemctl start myservice

systemctl status myservice

journalctl -u myservice

· You have a multi-threaded application randomly crashing. How do you debug?


· · CPU usage suddenly goes to 100%. What steps do you take?

· · One thread is blocked forever. How do you investigate?

· · How do you find memory leaks in Linux?

· · Difference between top, htop, ps, vmstat, strace?

· · How would you trace system calls of a process?

· · How do you debug race conditions?

A. BASIC (Must-Do)

1. Protect a Shared Counter

Problem

Two threads increment a global counter safely.

Binary Semaphore as Mutex

Problem

Use a binary semaphore instead of a mutex to protect a critical section.

Thread Execution Order

Problem

Ensure Thread B executes only after Thread A finishes.

What is a thread? How is it different from a process?

· A thread is the smallest unit of execution within a process.

· · It represents a single sequence of instructions that can be scheduled and


executed by the CPU.

· · Multiple threads can exist within the same process, sharing the same
memory space (code, data, heap) but having their own stack and registers.

Aspect Process Thread


Independent program in A lightweight subunit of a
Definition
execution process
Shares address space with
Has its own separate
Memory other threads in the same
address space
process
Higher (due to separate Lower (shares resources, less
Creation cost
memory and resources) overhead)
Aspect Process Thread
Inter-process
Threads communicate via
Communication communication (IPC)
shared memory directly
needed
Processes are isolated from Threads are not isolated; share
Isolation
each other memory
Scheduled independently Scheduled by OS but within
Scheduling
by OS process context

What is a process?

A process is an instance of a running program.

It includes the program’s code, data, heap, and its own execution context like program counter,
registers, and stack.

Each process has its own separate address space and resources.

The operating system manages processes, scheduling them to run on the CPU.

What are the benefits of multithreading?

· Improved Responsiveness:

In interactive applications, threads can keep the program responsive (e.g., UI thread remains
active while background threads do heavy work).

· Better Resource Utilization:

Multiple threads can run concurrently on multiple CPU cores, improving CPU utilization and
throughput.

· Faster Execution:

· Parallel execution of tasks can speed up processing by dividing work among threads.

· Simplified Program Structure:

Threads can simplify the design of programs that perform multiple simultaneous tasks (e.g.,
server handling multiple client requests).

What is the difference between user-level threads and kernel-level threads?

User-Level Threads Kernel-Level Threads


Aspect
(ULT) (KLT)
Managed by a user-
Managed directly by the
Management level thread library
OS kernel
(in user space)
Kernel does not Kernel knows and
Kernel
know about these manages them
awareness
threads individually
Creation/Context Fast and efficient, no Slower, involves system
User-Level Threads Kernel-Level Threads
Aspect
(ULT) (KLT)
kernel mode switch calls and kernel mode
switch overhead
needed switching
User-level scheduler Kernel scheduler
Scheduling
schedules threads schedules threads
Only the thread that
If a thread blocks on
Blocking system makes the blocking call
a system call, entire
calls blocks; other threads can
process blocks
run
Limited — kernel sees
True concurrency —
Concurrency on only one process
threads can run in
multiprocessors thread, so no real
parallel on multiple CPUs
parallelism
Portable across OSes OS-specific (kernel
Portability
(library-based) implementation)
Many green threads, POSIX threads (pthreads),
Examples
early Java threads Windows threads

Explain how thread creation works in POSIX threads (pthreads).

What is the lifecycle of a thread?

What are race conditions? How can they occur in multithreaded programs?

What is a critical section? How do you protect it?

Explain thread cancellation. How does it work in pthreads?


What is thread-local storage?

How do you pass arguments to a thread function in pthreads?

Synchronization Interview Questions

What is a mutex? How does it work?

Difference between a mutex and a semaphore?

What is a binary semaphore? How is it different from a mutex?

Explain deadlock. What are its necessary conditions?

How can you prevent or avoid deadlocks?

What is priority inversion? How can it be solved?


What are condition variables? How are they used?

Explain the producer-consumer problem and how you would solve it with semaphores.

What are spinlocks? When would you use them instead of mutexes?

How do you implement a reader-writer lock?

Explain barriers and their use cases in multithreaded programs.

What are reentrant functions? Why are they important in threading?

You might also like